why doesn't %let create a local macro variable?
Asked Answered
O

1

6

I always thought that %let creates a local variable if used inside of %macro . . . %mend

But when I run this code , the SAS log shows GLOBAL TESTVAR value1

%let testVar = value2; 
%macro test; 
%let testVar = value1; 
%mend;   

%test 

%put _all_;

So, I can't understand why the value of the global variable testVar changed to value1 . I was expecting it to be unchanged value2 . The %let statement inside the %macro should have impacted ONLY the local symbol table.

SAS documentation says:

When the macro processor executes a macro program statement that can create a macro variable, the macro processor creates the variable in the local symbol table if no macro variable with the same name is available to it

Ogburn answered 17/12, 2014 at 18:58 Comment(0)
B
7

The key is 'if no macro variable with the same name is available to it' - in this case, a macro variable with the same name is available, because you've already defined testVar as a global.

You can either give it a name that isn't shared with a global, or explicitly declare it as local:

%let testVar = value2; 
%macro test; 
    %local testVar;
    %let testVar = value1; 
%mend;   

%test 
Brent answered 17/12, 2014 at 19:23 Comment(2)
Thanks, I get it now. I was confused with the SAS example : %let new=inventry; %macro name2; %let new=report; . . Ogburn
@Ogburn You should always explicitly declare variables in macros as local (if you expect them to be local). Failing to do so can lead to some difficult to debug code if your macro happens to call other macros (or is being called by another macro).Melburn

© 2022 - 2024 — McMap. All rights reserved.