连接引用的宏变量

时间:2014-08-27 18:37:54

标签: sas concatenation sas-macro

我只是想连接两个引用的宏变量,但似乎没有一个简单的方法。

说我们有:

%LET VAR1="This is not the greatest song in the world";
%LET VAR2="this is just a tribute.";

%LET TRIBUTE=%SYSFUNC(CATX(%STR( ),&VAR1,&VAR2));
%PUT &TRIBUTE;

我其实想要:

  "This is not the greatest song in the world this is just a tribute."

但上面的代码确实产生了:

"This is not the greatest song in the world"  "this is just a tribute."

所以我尝试放%QUOTE()%BQUOTE等。在&VAR1%VAR2附近希望取消屏蔽引号,但我得到了相同的结果。

唯一对我有用的是:

 %LET TRIBUTE="%SUBSTR(&VAR1.,2,%LENGTH(&VAR1.)-2) %SUBSTR(&VAR2.,2,%LENGTH(&VAR2.)-2)"; 

但这很难看,而且可以很快地变得冗长。 有没有更好的方法来做到这一点?

2 个答案:

答案 0 :(得分:4)

我要解释乔的真实回答'这是 - 不要在宏变量中存储引号。宏语言中的单引号和双引号与任何其他字符没有区别。你应该做的是推迟引用引号,直到你真正需要它们为止。这将导致更清晰,更灵活,更易于阅读和无错误的代码。

<强>代码:

请注意,我已删除引号并连接字符串,我只是一个接一个地列出它们:

%LET VAR1=This is not the greatest song in the world;
%LET VAR2=this is just a tribute.;
%LET TRIBUTE=&VAR1 &VAR2;

示例1

在第一个示例中我们使用%put语句时,不需要引号来打印出所需的字符串 - 因此我将引号排除在外:

%PUT &TRIBUTE;

输出:

This is not the greatest song in the world this is just a tribute.

示例2

报价是必需的,因为我们现在处于数据阶段:

data _null_;
  put "&TRIBUTE";
run;

输出:

This is not the greatest song in the world this is just a tribute.

请注意,这两个示例都假设您实际上并不想将引号打印到屏幕上。

答案 1 :(得分:2)

您可以使用COMPRESS执行此操作。

%LET VAR1="This is not the greatest song in the world";
%LET VAR2="this is just a tribute.";


%let VAR3=%sysfunc(compress(&VAR1,%str(%")));
%put &=var1 &=var3;

删除引号有点棘手,但它确实有效。

您也可以在FCMP函数或函数式宏中执行此操作;这是一个例子。

%macro unquote_string(string=);
%sysfunc(compress(&string.,%str(%'%")))
%mend unquote_string;

%let VAR3="%unquote_string(string=&var1.) %unquote_string(string=&var2.)";
%put &=var3.;

请注意,您不应使用CAT函数来连接宏变量。它们只是文本,因此一个接一个地键入它们会自动连接它们。

但是,对于“有更好的方式”问题的真正答案是不将引号存储在宏变量中。大多数情况下,您应该存储没有引号的宏变量,并在需要时在引号内使用它。 SAS Macros不会将引号视为特别的 - 它们只是字符串中的一个字符 - 所以它们没有特定的工具来处理这个问题。

相关问题