Reputation: 4463
Suppose in Stata I wish to define a program:
capture program drop myprg
program define myprg
syntax varlist
foreach var of varlist `varlist' {
disp "`var'"
}
end
I want my program to be able to accept both names of variables that exist in my dataset and names of non-existent variables. If the variable exists, it displays the name. Otherwise, it does nothing.
Suppose my dataset has two variables: age1
and age2
. The current output is:
. myprg age1
age1
. myprg age*
age1
age2
. myprg varThatDoesntExist
variable varThatDoesntExist not found
r(111);
Instead, the desired output for the last command is:
. myprg varThatDoesntExist
.
How can I get this functionality?
Upvotes: 3
Views: 644
Reputation: 37208
See the help
for syntax
. The specification namelist
generalises varlist
to print out any name, existing and legal variable name or not.
program myprg
syntax namelist
foreach var of local namelist {
disp "`var'"
}
end
A variant requested after first posting of this question was to print actual variable names and to ignore anything else. For that you need to set up your own parsing. Again, see the help
for syntax
. You need something like
program myprg
version 8.2
syntax anything
local varlist
foreach thing of local anything {
capture unab Thing : `thing'
if _rc == 0 local varlist `varlist' `Thing'
}
foreach v of local varlist {
di `"`v'"'
}
end
Upvotes: 3