宏指定默认值,避免变量名称冲突

时间:2018-04-13 16:22:01

标签: sas sas-macro

这是我想在宏功能开始时调用的一个小宏。

相当于%if not %length(&x) %then %let x = &val

我想使用它,因为它更具可读性,并且可以帮助我解析我的代码以构建文档(我需要使用正则表达式,因为我无法安装外部软件)。

%macro def
/*---------------------
Assign default value
---------------------*/
(_x_data_x_  /* variable name (to be passed raw without &) */
,value       /* default value */
);
%if not %length(&&&_x_data_x_) %then %let &_x_data_x_ = &value;
%mend;

以下是它的工作原理:

%macro test(a,b);
  %def(b,&a)
  %put "&b";
%mend;

%test(%str(,)); /* prints "," */

我选择了不常见的参数名_x_data_x_,因为宏输入的值等于参数的名称(即如果我的b参数名为_x_data_x_),则会失败。

除了选择晦涩难懂的名字外,我能否真正做到安全?

1 个答案:

答案 0 :(得分:2)

这是正确的方法。

您可以通过添加检查来使宏更加健壮:

 %* Prevent self reference because 
 %* assignment will not bubble to containing scope;

 %if %upcase(%superq(x_data_x)) eq X_DATA_X %then %do;
   %put ERROR: x_data_x=%superq(x_data_x) is not allowed;
   %abort cancel;
 %end;

 %* Prevent reference to non-existent because
 %* assignment will automatically localize 
 %* and not bubble to containing scope;

 %if not %symexist (%superq(x_data_x)) %then %do;
   %put ERROR: x_data_x=%superq(x_data_x) is invalid;
   %put ERROR: %superq(x_data_x) does not exist in callee scope;
   %abort cancel;
 %end;
相关问题