SAS Tips- Deal with Multi Ampersand
I came across a very interesting question a few days ago and I'd like to share with you.
Think about this program:
%let one = two; %let two = three; %let three= four; %let four = five; %put &one;
What is the output of this %put statement? Certainly it's two.
Now we add one more ampersand.
%let one = two; %let two = three; %let three= four; %let four = five; %put &&one;
Would it be three this time? No. The output is still two.
Why? Because SAS treats "&&" as "&".
But what should we do if we want to output "three"?
Try this:
%put &&&one;
When SAS meets "&&&", it treats the first two ampersands as one, and holds them. The third ampersands combined with "one" make up a complete macro variable, which is resolved to "two". Then the held ampersand and "two" are further resolved to "three".
If you understand this rule, no matter how many ampersands you meet, you could figure out the correct answer.
Try "&&&&&&&one" and "&&&&&&&&&&one".
The correct answers are "four" and "three". Did you get the right answers?
Now we are able to give this chart, showing the most fundamental pattern hidden behind the rule.
Do this until the number reaches zero. And the points you get is the times the macro variable gets resolved.
For example, we have 7 "&". It is odd so minus 1, getting 1 point. Now we have 6, which is even so divide by 2, getting no points. Then we get 3, which is odd, so minus 1 and get 1 point. The last two steps is always the same: 2/2=1, 1-1=0. We get 3 points in total so the macro variable are going to be resolved for three times.
one-two, two-three, three-four. OK, four is the answer.
Moreover, you could also figure out in which way we can make it more times to resolve. That is the inverse process of the above calculation. Multiply the number by 2 and then plus 1. Like this 2(2(X+1)+1)+1.









