简体   繁体   English

数据步骤内的宏执行

[英]Macro execution inside data step

I have the following macro which I will use inside a data step:我将在数据步骤中使用以下宏:

%global var3;

%macro add(var1,var2);
    %let var3 = %eval(&var1+&var2);
%mend;

I don't understand the results of the following data step:我不明白以下数据步骤的结果:

%let var3 = 2;

data test;
    put "The value of var3 is &var3";
    x = 3 - &var3;
    %add(7,3);
    %put &=var3;
run;

From what I understand, macro statements are executed before compilation of a data step.据我了解,宏语句是在编译数据步骤之前执行的。 So in this case macro %add is executed first and then %put statement.所以在这种情况下,宏 %add 先执行,然后 %put 语句。 However, the value of x is 1, not -7.但是,x 的值为 1,而不是 -7。 And also put statement prints The value of var3 is 2, instead of 10. I am confused.并且还把语句打印出来 var3 的值是 2,而不是 10。我很困惑。

Let's look at what happens.让我们看看会发生什么。

 69         %global var3;
 70         
 71         %macro add(var1,var2);
 72             %let var3 = %eval(&var1+&var2);
 73         %mend;
 74         
 75         %let var3 = 2;
 76         options symbolgen mprint;
 77         data test;
 SYMBOLGEN:  Macro variable VAR3 resolves to 2
 78             put "The value of var3 is &var3";
 79             x = 3 - &var3;
 SYMBOLGEN:  Macro variable VAR3 resolves to 2
 80             %add(7,3);
 SYMBOLGEN:  Macro variable VAR1 resolves to 7
 SYMBOLGEN:  Macro variable VAR2 resolves to 3
 81             %put &=var3;
 SYMBOLGEN:  Macro variable VAR3 resolves to 10
 VAR3=10
 82         run;
 
 The value of var3 is 2

So, SAS goes to run the macro pass, as you say before data step compilation, and turns the code into this...所以,SAS 去运行宏传递,正如你在数据步骤编译之前所说的,并将代码变成这样......

data test;
  put "The value of var3 is 2";
  x = 3 - 2;
  %let var3 = %eval(7+3);
  %put 10;
run;

You're right that SAS does handle the macro language before compilation, but that doesn't mean it happens before SAS begins to prepare the data step for compilation. SAS 在编译之前处理宏语言是对的,但这并不意味着它发生在 SAS 开始准备编译数据步骤之前。 The macro language pass creates the final data step, but it still happens sequentially - so SAS looks at line 77, sees no macro variables, finalizes it;宏语言传递创建了最后的数据步骤,但它仍然按顺序发生——所以 SAS 查看第 77 行,没有看到宏变量,完成它; it looks at line 78, sees &var3, turns it into 2, finalizes that line;它查看第 78 行,看到 &var3,将其变成 2,最终确定该行; looks at line 79, etc.查看第 79 行等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM