Concatenate quoted macro variables

Pane picture Pane · Aug 27, 2014 · Viewed 13.8k times · Source

I'm just trying to concatenate two quoted macro variables but there doesn't seem to be an easy way.

Say we have:

%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;

I actually want:

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

But the above code actually yields:

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

So I try putting %QUOTE(),%BQUOTE,etc. around &VAR1 and %VAR2 in hopes of unmasking the quotes but I get the same result.

The only thing that works for me is:

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

But this is ugly and can get lengthy really fast. Is there not a better way to do this ?

Answer

Robert Penridge picture Robert Penridge · Aug 27, 2014

I'm going to paraphrase Joe's 'real answer' which is - do not store quotes in the macro variable. Single and double quotes in the macro language are no different to any other character. What you should do is delay introducing the quotes until you actually need them. This will result in much cleaner, more flexible, easier to read, and bug-free code.

Code:

Notice I've removed the quotes and to concatenate the strings I'm just listing them one after the other:

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

Example 1

No quotes are needed to print out the desired string as we are using a %put statement in this first example - for this reason I left the quotes out:

%PUT &TRIBUTE;

Output :

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

Example 2

Quotes are required because we are now in data-step land:

data _null_;
  put "&TRIBUTE";
run;

Output :

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

Note that both of these examples assume you don't actually want to print the quotes to the screen.