Danny
Danny

Reputation: 203

appending a counter to a string obtained by dereferencing macro variable

how do I get so inside the loop I get: var1, var2? I know it does not work to dereference j but the meaning gets more clear to what I want to do (see below)

%let var1 = apple;
%let var2 = pear;


data _null_;
do j=1 to j=2;
put &var&j; //<---?
end;
run;

in the log:

apple
pear

Upvotes: 0

Views: 46

Answers (2)

Tom
Tom

Reputation: 51581

Sounds like you want to resolve a macro variable whose name you are creating by appending the value of another macro variable to some constant prefix.

If you try to use code like this:

%let var1 = apple;
%let var2 = pear;
%let j=1 ;
%put &var&j; 

You will get an error message that the macro variable named VAR does not exist.

You need to signal to the macro processor that it needs to delay trying to evaluate &var until after the suffix has been appended. The way to do this is to double the first &.

%put &&var&j; 

The presence of double &'s will cause the macro processor to replace them with a single & and set a reminder to itself the re-scan the result for more macro variable references.

So the first pass will replace && with & and replace &j with 1. Then the second pass will replace &var1 with apple.

Upvotes: 0

Reeza
Reeza

Reputation: 21274

As noted above, J is not a macro variable so you cannot use it as such. You can use the SYMGET function to retrieve the value though. Assuming you want data step logic for some reason:

data _null_;
do i=1 to 2;
    x= symget(catt('var', i));
    put x;
end;
run;

Upvotes: 4

Related Questions