Reputation: 21
In my code I've many macros inside others on many levels. Most of macro variables are the same (dates), but sometimes I'd like to run a macro with different date - then my variables collide.
How can I state that all variables that will appear in the macro should be local without using %local so many times? For nested macros values of variables from deeper level do infect variables in upper levels.
Upvotes: 2
Views: 281
Reputation: 949
Another option is to define the variables as macro parameters on the macro statement line. Below is a simple program that creates a global macro variable named DATE, then defines a macro with a parameter which is also named DATE. In addition, the macro calls itself with a different date value(1).
options nosource nonotes;
%let date = '01jan2011'd;
%put Global DATE = &date;
%******************************************************************************;
%macro test_macro_level(date=,nest_level=);
%put INSIDE MACRO - Nest Level=&nest_level : DATE=&date;
%if %eval(&nest_level = 1) %then %do;
%test_macro_level(date='01mar2011'd,nest_level=2);
%put INSIDE MACRO, AFTER NESTING - Nest Level=&nest_level : DATE=&date;
%end;
%mend test_macro_level;
%******************************************************************************;
%test_macro_level(date='01feb2011'd,nest_level=1);
%put Return to Global: Date=&date;
The log file then reads:
Global DATE = '01jan2011'd
INSIDE MACRO - Nest Level=1 : DATE='01feb2011'd
INSIDE MACRO - Nest Level=2 : DATE='01mar2011'd
INSIDE MACRO, AFTER NESTING - Nest Level=1 : DATE='01feb2011'd
Return to Global: Date='01jan2011'd
(1) Please note that the iterative macro is for example only and should in no way pollute your own code.
Upvotes: 1
Reputation: 8513
You must explicitly list them with %local everytime. Unfortunately, there is no shortcut.
As an aside, if you are having problems troubleshooting nested macros one tip that made it easier for me was to change my standards so that I never modified the value of any macro (input) parameters. This simple concept makes debugging much easier.
And if you happen to have %include statements in your macros then add the 'option source2' so that the source code from these are also shown in the log.
Cheers Rob
Upvotes: 1