Macro Do-List

From sasCommunity
Jump to: navigation, search

This macro illustrates picking an item from a list and returning a macro call with I and Item as parameters.

keywords: Encapsulation

Macro Do-List

 /*    name: do_list.sas
   location: <UNC>\SAS-site\macros
description: macro function: pick items from list, call macro
    purpose: list processing demo of encapsulation of do loop
RJF2 4/7/2013 7:44:31 AM
usage: /**** * **
options mprint source2;
%do_list()
options nomprint nosource2;
%do_list(list =1 22 333 4444)
%do_list(list =A+bc+def+g
        ,delimiter=+
        )
%Macro put_note(i=,item=);
%put note: i=&i item=&item;
%mend;
%do_list(list =1a 22b c333 44d44
        ,macroname = put_note)
/********/
%macro do_list
       (start     =1
       ,stop      =%eval(%sysfunc(countc(&List,&delimiter))+1)
       ,delimiter =%str( )
       ,list      =a b
       ,macroname =put note
       ,macroparms=%nrstr(i=&I,item=&Item)
       ,semicolon =0
       ,testing   =0
       );
%Let Testing = %eval(&testing
               or (    %sysfunc(getoption(mprint )) eq MPRINT
                   and %sysfunc(getoption(source2)) eq SOURCE2
                  );
%local I Item;
%let I    = &Start;
%let Item = unassigned;
%if &Testing %then %do;
    %put note: &SysMacroName parameters;
    %put _local_;
    %end;
%do I = &Start %to &Stop;
    %let Item = %scan(&List,&I,&delimiter);
    %&MacroName(%unquote(&MacroParms))
    %if &Semicolon or %scan(&MacroName,1) eq put %then %do;
        ;
        %end;
    %end;
%mend do_list;

Program Do-List test

 /*    name: do_list-test.sas
 /**** * **/
options mprint source2;
%do_list()
options nomprint nosource2;
%do_list(list =1 22 333 4444)
%do_list(list =A+bc+def+g
        ,delimiter=+
        )
%Macro put_note(i=,item=);
%put note: i=&i item=&item;
%mend;
%do_list(list =1a 22b c333 44d44
        ,macroname = put_note)

Log:

1          options mprint source2;
2          %do_list()
note: DO_LIST parameters
DO_LIST LIST a b
DO_LIST I 1
DO_LIST MACROPARMS �i��I�item��Item�
DO_LIST DELIMITER � �
DO_LIST TESTING 1
DO_LIST ITEM unassigned
DO_LIST START 1
DO_LIST STOP %eval(%sysfunc(countc(&List,&delimiter))+1)
DO_LIST MACRONAME put note
DO_LIST SEMICOLON 0
note(i=1,item=a)
note(i=2,item=b)
3          options nomprint;
4          
5          %do_list(list =1 22 333 4444)
note(i=1,item=1)
note(i=2,item=22)
note(i=3,item=333)
note(i=4,item=4444)
6          
7          %do_list(list =A+bc+def+g
8                  ,delimiter=+
9                  )
note(i=1,item=A)
note(i=2,item=bc)
note(i=3,item=def)
note(i=4,item=g)
10         
11         %Macro put_note(i=,item=);
12         %put note: i=&i item=&item;
13         %mend;
14         
15         %do_list(list =1a 22b c333 44d44
16                 ,macroname = put_note)
note: i=1 item=1a
note: i=2 item=22b
note: i=3 item=c333
note: i=4 item=44d44

References


--Ronald_J._Fehd macro.maven == the radical programmer 09:01, 7 April 2013 (EDT)