Search code examples
sassas-macroproc-sqlsas-studio

SAS Studio - parentheses affecting how sysfunc function resolves macro variable


I have a counter in my code that is as follows: %let counter = %sysfunc(countw(&&CLMNS&j.)); However this does not work properly for some macro variables. For variable_1, which contains the values Parent_Name, Name the counter returns as 3 (should be 2). For variable_2, which contains Alt_Parent_Name, Alt_Name the counter correctly returns a value of 2.

If I add a pair of parentheses, so it now is: %let counter = %sysfunc(countw((&&CLMNS&j.)));, it now correctly outputs a value of 2 for both variable_1 and variable_2.

I have read through the help cards to no avail and would like to figure out why this occurs and what the extra parentheses do. I am mostly confused by the inconsistency of the result in the first instance.


Solution

  • Perhaps this helps:

    SAS will break it down in the following order:

    %let counter = %sysfunc(countw(&&CLMNS&j.));

    1. Two ampersands (&&) resolves to one ampersand (&) and the scanner continues.
    2. Resolve &j. in the global symbol table. E.g. to 1.
    3. Then resolve &CLMNS1 in the global symbol table. E.g. to variable_1 (which would have to be resolved with another ampersand) or just Parent_Name, Name.
    4. Replace the values in the input stack:
      • %let counter = %sysfunc(countw(Parent_Name, Name));

    Now you can perhaps see what is going wrong. When the compiler continues, it will understand Name as the optional argument <character(s)> in countw.

    What you want is instead to mask the output of &&CLMNS&j. for the macro processor. I.e. use %NRSTR:

    %let counter = %sysfunc(countw(%NRSTR(&&CLMNS&j.)));
    

    Expected global symbol table:

    %PUT _ALL_;
    GLOBAL J 1
    GLOBAL CLMNS1 parent_name, name
    GLOBAL CLMNS2 alt_parent_name, alt_name
    AUTOMATIC ....
    

    These resources might be relevant for you:

    1. Going Under the Hood: How Does the Macro Processor Really Work?
    2. The Ampersand (&) Challenge, Single, Double or more?
    3. SAS Help Center: COUNTW
    4. SAS Help Center: %STR and %NRSTR Functions