Quoting macro variables - keep it simple

It's a good idea to quote your macro variables when using them in %if statements and the like. This protects your code from macro variable values that contain reserved words or punctuation which might otherwise cause it to crash. For example, in the statement:

%if &title = %then %let title = Default title;

setting title to Shoe Sales by Quarter will work perfectly, but setting title to Stocks and Shares Earnings will make your program crash. That's because the latter value contains and, so the %if condition resolves to:

%if Stocks and Shares Earnings = %then %let title = Default title;

SAS interprets the "and" as part of a logical expression, but the rest of the condition doesn't fit, so you get an error.

To prevent this type of problem, you should always quote macro variables when doing this sort of textual comparison. SAS provides a bewildering range of macro quoting functions, but none of them is necessary in this situation - simply use double quotes as you would in a data step:

%if "&title" = "" %then %let title = Default title;

This is somewhat of a hack, because it's not doing quite what it appears to: the quotes aren't simply there as delimiters to tell SAS where the string starts and ends, as they would be in a data step - to the macro processor, the quotes are actually part of the strings being compared. That's why it's important to use double quotes on both sides of the equals sign - if you used single quotes on the right-hand-side, and assuming title is set to an empty string, the condition would resolve to:

%if "" = '' %then %let title = Default title;

and the macro processor considers those two strings to be unequal.

Use double quotes on both sides, though, and you (a) protect your code from any reserved words appearing in your macro variable, and (b) make the code much more readable and familiar than if you'd gone with %str() or one of its many relatives.

Comments