1
votes

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
3
Are you trying to count the number of characters in &temp (11 in your sample) or the number of quoted strings (3 in your sample)?Don Hopkins
Number of quoted strings - edited to clarifycacti5

3 Answers

4
votes

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');
0
votes

THis works for me:

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

%let count = %sysfunc(countw("&temp", ","));
%put Number of elements = &count.;

Results:

8002  %put Number of elements = &count.;
Number of elements = 3
0
votes

The %quote function might be helpful here to mask the quotation marks:

%let count = %sysfunc(countw(%quote(&temp), ","));
%put Number of elements = &count.;