Saturday, December 7, 2013

SAS: Looping thru a macro variable

Source code:

%macro doit(FOREACH=);
%local i j ;
%let j = 1 ;
%do %while(%scan(&FOREACH,&j) ne ) ;
   %let i = %scan(&FOREACH,&j) ; 

   %put &FOREACH &j &i;
   %let j = %eval(&j+1) ;
%end ;
%mend doit;

%doit();                 * none ;
%doit(FOREACH=A);        * one only, no parenthesis ;
%doit(FOREACH=(B));      * one only, with parenthesis ;
%doit(FOREACH=(C,D));    * two, comma separated, with parenthesis ;
%doit(FOREACH=(E F G));  * three, space separated, with parenthesis ;



Output from log:


125  %macro doit(FOREACH=);
126  %local i j ;
127  %let j = 1 ;
128  %do %while(%scan(&FOREACH,&j) ne ) ;
129     %let i = %scan(&FOREACH,&j) 

130     %put &FOREACH &j &i;
131     %let j = %eval(&j+1) ;
132  %end ;
133  %mend doit;
134
135  %doit();                 * none ;
136  %doit(FOREACH=A);        * one only, no parenthesis ;
A 1 A
137  %doit(FOREACH=(B));      * one only, with parenthesis ;
(B) 1 B
138  %doit(FOREACH=(C,D));    * two, comma separated, with parenthesis ;
(C,D) 1 C
(C,D) 2 D
139  %doit(FOREACH=(E F G));  * three, space separated, with parenthesis ;
(E F G) 1 E
(E F G) 2 F
(E F G) 3 G



No comments:

Post a Comment