Search code examples
sassas-macro

Length of a SAS macro variable that contains quotes and commas


Let the sample macro variable be

%let temp="A","B","C";

How do you get the array length of this macro variable, which includes quotations and commas? For example, I would want to return length 3.

%let length_of_temp=%sysfunc(SOME_FUNC(&temp.));
%put length=length_of_temp;

LOG: length=3

Preferably I would want to do it using one established SAS function or line of code, not creating a new function for processing. Here is what I have attempted so far:

  • countw("&temp.",","): the quotes create an error when trying to convert it to a string.

NOTE: Line generated by the macro variable "TEMP". 4
""A","B","C"

NOTE 49-169: The meaning of an identifier after a quoted string might change in a future SAS release. Inserting white space between a quoted string and the succeeding identifier is recommended.

ERROR 388-185: Expecting an arithmetic operator.

  • countw(&temp.,",") and count(&temp.): typical error of function call has too many arguments
  • count((&temp.)) and dim((&temp.))
  • variations using %superq on the above

Solution

  • Use macro quoting on your macro variable value so that commas do not cause trouble for call to countw() function. Use the q and possibly the m optional third argument to the countw() function to let it know not to count delimiters that are inside the quotes.

    %let temp="A1,a2","B","C";
    %let count = %sysfunc(countw(%superq(temp),%str(,),mq));
    

    If you want to calculate the count in a data step then instead of macro quoting you can use the symget() function to retrieve the value of the macro variable.

    count = countw(symget('temp'),',','mq');