2017-06-22 173 views
1

有沒有辦法將宏作爲參數傳遞給宏?SAS - 將宏傳遞給宏

%macro outer_macro(macro); 
    %do i=1 %to 5; 
    &macro 
    %end; 
%mend outer_macro; 

%macro inner_macro; 
    /* do something usefull */ 
%mend inner_macro; 

%outer_macro(%inner_macro) 

這個例子不工作,當然。

回答

5

您將使用宏引用來完成此操作。

一個簡單版本的例子:

%macro outer_macro(macro); 
    %put Starting outer macro; 
    %unquote(&macro) /* %unquote removes the NRSTR escape characters */ 
    %put Ending outer macro; 
%mend outer_macro; 

%macro inner_macro; 
    %put Starting inner macro; 
    proc print data=sashelp.class; 
    run; 
    %put Ending inner macro; 
%mend inner_macro; 

%outer_macro(%nrstr(%inner_macro)) /* %nrstr is execution-time quoting, so %inner_macro is passed and not treated as a macro until %unquote removes the quoting */ 

涉及到像一個循環,你只要確保一切都建立起來,可以將循環迭代 - 一個辦法就是追加()與循環。

%macro outer_macro(macro); 
    %put Starting outer macro; 
    %do i = 1 %to 19; 
     %unquote(&macro)(n=&i.) /* resolves to %inner_macro(n=&i.) */ 
    %end; 
    %put Ending outer macro; 
%mend outer_macro; 

%macro inner_macro(n=); 
    %put Starting inner macro; 
    proc print data=sashelp.class(obs=&n. firstobs=&n.); 
    run; 
    %put Ending inner macro; 
%mend inner_macro; 

%outer_macro(%nrstr(%inner_macro)) 
2

爲什麼不按名稱傳遞宏?

%macro outer_macro(macro); 
    %put Starting &sysmacroname - MACRO=%superq(macro); 
    %&macro 
    %put Ending &sysmacroname; 
%mend outer_macro; 

%macro inner_macro(dsn); 
    %put Starting &sysmacroname - &=dsn; 
    proc print data=&dsn; 
    run; 
    %put Ending &sysmacroname; 
%mend inner_macro; 

%outer_macro(inner_macro(sashelp.class)) ; 

打開MPRINT的結果LOG。

Starting OUTER_MACRO - MACRO=inner_macro(sashelp.class) 
Starting INNER_MACRO - DSN=sashelp.class 
MPRINT(INNER_MACRO): proc print data=sashelp.class; 
MPRINT(INNER_MACRO): run; 

NOTE: There were 19 observations read from the data set SASHELP.CLASS. 
NOTE: PROCEDURE PRINT used (Total process time): 
     real time   0.04 seconds 
     cpu time   0.00 seconds 


Ending INNER_MACRO 
Ending OUTER_MACRO