6.3.09

Use of ampersands and semicolons in SAS macros

Prepared by Jose Abraham


Single, double and triple ampersands

Multiple ampersands can be used to allow the value of a macro variable to become another macro variable reference. The macro variable reference will be rescanned until the macro variable is resolved.

The following demonstrates how macro variables with multiple ampersands are resolved. There are
4 macro variables

Macro variable :Value
A : CATCH
B : STUMP
C : RUN
HIT : A

Resolving a macro variable:

&VARNAME references a macro variable. The rule is that the scanner reads from left to right.

1. If we put one ampersand i.e., ‘&HIT’ then the macro variable hit resolves to ‘A’.

2. If we put two ampersands then the two ampersands resolve to one and scanner continues. i.e., ‘&&HIT’
On the first scan - ‘&&’ resolves to ‘&’ and ‘HIT’ held as token.
On the second scan – ‘&HIT’ resolves to ‘A’.

3. If we put three ampersands i.e., ‘&&&HIT’
On the first scan -‘&&’ resolves to & and the remaining &HIT resolves to ‘A’ and the it results ‘&A’
On the second scan –‘&A’ resolves to ‘CATCH’



Single and double semi colons
When creating macros for programming, sometimes we would like to generate a dynamic SAS statement within a macro %DO loop. For example if we want to run a print procedure inside a macro and refer to a set of macro variables within the VAR statement.

proc print;
var
%do i = 1 %to &max;
&&var&i
%end;;
run;

Consider a simple program containing this %DO loop in a macro

data one;
input A $ B C D E;
datalines;
a 12 16 18 20
;
run;

%let var1=A;
%let var2=B;
%let var3=C;
%let var4=D;
%let var5=E;
%let max=4;
%let indt=one;

%macro prnt;
proc print data=&indt.;
var
%do i = 1 %to &max.;
&&var&i
%end;;
run;
%mend;

%prnt;

In this program, there are two consecutive semicolons used after the %end statement which is not common in a simple SAS program. Here the first semicolon closes the %END and the second semicolon closes the VAR statement. And if we run this macro it will generate the following SAS statements

proc print data=one;
var a b c d;
run;

and it produces the result

No comments: