I think this probably isn't a useful technique, but I'll answer it anyway.
I'll also assume that &Key1..n
may have values other than the number stored in them, and you want those values collected into the &MasterKey1..n
variables.
What you'd need to do is use a nested loop, and to know a bit about how macro variables resolve.
%let key1=A;
%let key2=B;
%let key3=C;
%global MasterKey1 MasterKey2 MasterKey3; *so they work outside of the macro;
%macro create_master(numKeys=);
%do master=1 %to &numKeys; *Outer loop for the MasterKeys we want to make;
%let temp=;
%do keyiter = 1 %to &master; *Inner loop for the keys that fall into the MasterKey;
%let temp = &temp.&&Key&keyiter.; *&& delays macro variable resolution one time.;
%end;
%let MasterKey&master.=&temp.;
%end;
%mend create_master;
%create_master(numkeys=3);
%put &=MasterKey1 &=MasterKey2 &=MasterKey3;
The magic here is &&
. Basically, during macro variable parsing, you deal with one or two &s at a time. If it helps put some %put
statements inside the loop to see how it works.
To start with, let's jump in towards the end. On this iteration, &temp=AB
&Keyiter=3
and &Key3=C
.
0. &temp.&&Key&keyiter
1. AB&Key3
2. ABC
So from 0 to 1, the parser sees &temp.
, the period denoting the end of one variable, so it looks up what is that: &temp.=AB
and replaces it with AB. Then it sees two &
s, and replaces them with one &
but doesn't attempt to resolve anything with them. Then it sees Key
, no ampersands there so nothing to do. Then it sees &keyiter
, okay, replace that with 3
.
Then from 1 to 2, it sees AB
, ignores it as it should. Then it sees &Key3
(two ampersands became one don't forget), and now it knows to resolve that to C
, which it does - thus ABC.