Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the ith word in a macro variable list

Tags:

macros

sas

%let TableList = TableA TableH TableB TableG;

Words in &TableList are separated by ' '.

How can I retrieve certain word to do the following?

I do not know the number of words in the tablelist and would like to get the nth word from the list.

Given i = 4,

data &&table&i.; /* &&table&i. will resolve to TableG */
set have;
[..];
run;
like image 926
Lovnlust Avatar asked Nov 18 '25 21:11

Lovnlust


2 Answers

The short answer is to use the %scan function:

%put %scan(&tablelist,4,%str( ));

The third argument specifies that %scan should count only spaces as delimiters. Otherwise, it will also treat all of the following characters as delimiters by default:

. < ( + & ! $ * ) ; ^ - / , % |

Given the list you have, you can use a %do loop to add the macro variables to a list:

/* initialise a counter macro variable */
%let k = 1;

/* iterate through tablelist until a value is not found */
%do %until (%scan(&tablelist,&k,%str( )) = );
  %let table&k = %scan(&tablelist,&k,%str( )); 
  %let k = &k + 1;
%end;

%let i = 4;
%put &&table&i;

N.B. this code only works inside a macro definition (that is a block of code delimited by %macro and %mend statements.

like image 108
mjsqu Avatar answered Nov 22 '25 04:11

mjsqu


I would have done the same %sysfunc(scan) trick as @mjsqu and as to answer your remaining question - of getting the last word because you don't know the number of words in the list, the easiest way I can think of is using array like below

%let all=word1 word2 word3 word4 word5;

%macro test;
data _NULL_;
array x[*] &all.;
Num=dim(x);
call symput("Num_of_words",num);
run;
%mend;
%test;

Now you know the total number of words so can find out the last word as well.

like image 23
in_user Avatar answered Nov 22 '25 04:11

in_user



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!