I'd like to use a little macro logic in open code (i.e., not within a macro) to control my program. Specifically, if a certain macro variable exists and has a certain value of interest, I'd like to execute a bit of code. This macro variable might not exist, or it might exist but have a value that I don't care about. So currently I first check that it exists with %symexist(), and then I check its value:
* do something if myMacroVar exists and equals 1;
%if %symexist(myMacroVar) %then %do;
%if &myMacroVar = 1 %then %do;
%put Do something here;
%end;
%end;
This fails because I'm using nested %if statements, which is not allowed in open code. So I'm wondering, is there a solution that works in open code, without nested %if statements?
I could of course just wrap the above code in a macro, and that works fine. But for stylistic reasons, I don't like that solution. It requires 3 extra lines of code (%macro statement, %mend statement, then calling the macro), and it creates a reusable macro which I have no intention of reusing.
Instead of nesting them you could do two tests. First test if the macro variable exist and then set a macro variable to test the condition. Preset the macro variable to false to catch the cases when the macro variable does not exist.
%let found=0;
%if %symexist(nosuchvar) %then %do;
%let found=%eval(&nosuchvar=1);
%end;
Then use the macro variable to control what code to run.
%if &found %then %do;
... code you want to run ...
%end;
You could always just force the macro variable to exist before trying to test its value.
%global nosuchvar;
But watch out trying to do that inside a macro definition since you cannot use %GLOBAL statement for a macro variable that already exists in an active local symbol table.
%if not %symexist(nosuchvar) %then %do; %global nosuchvar; %end;