I am having trouble returning the result of a program. Perhaps it is the scope of the variable, or I'm using the wrong class of program, or perhap a missing quote somewhere I am not sure.
The program works perfectly...other than returning the varlist fails..but the list it generates before trying to return it to the user is correct.
The program is designed to simply return a varlist of any 'substring' the user chooses.
Some pretend code to play with:
Code:
* Example generated by -dataex-. For more info, type help dataex clear input byte(d_this frm_d_this frm_d_dodd frm_p_hello frm_o_held frm_d_p_test1 d_another frm_blend_v1 frm_id) float(frm_tx_badsttuff_v1 frm_tx_bmorettuff_v2 frm_p_tx_nnmamicf_v3) 0 0 0 0 0 0 0 0 1 1 2 4 0 0 0 0 0 0 0 0 2 1 2 4 0 0 0 0 0 0 0 0 3 1 2 4 0 0 0 0 0 0 0 0 4 1 2 4 0 0 0 0 0 0 0 0 5 1 2 4 0 0 0 0 0 0 0 0 6 1 2 4 0 0 0 0 0 0 0 0 7 1 2 4 0 0 0 0 0 0 0 0 8 1 2 4 0 0 0 0 0 0 0 0 9 1 2 4 0 0 0 0 0 0 0 0 10 1 2 4 0 0 0 0 0 0 0 0 11 1 2 4 0 0 0 0 0 0 0 0 12 1 2 4 0 0 0 0 0 0 0 0 13 1 2 4 0 0 0 0 0 0 0 0 14 1 2 4 end
Code:
capture program drop findVarsWithSubstring
/*
program that finds any variables that match substring `sub'. The program avoids false positives that are part of a variable name.
can be used, for example, to locate variables with `sub' in them (eg., frm_ , d_, p_, s_, _t)
*** example use *****************************
ds
findVarsWithSubstring `r(varlist)', sub("d_") name(result)
*********************************************
*/
program define findVarsWithSubstring, sclass
syntax varlist(min=1), sub(string) [, NAME(string)]
*di "my varlist is currently: `varlist'"
*di "my substring is currently: `sub'"
* create local to store this varlist
local returnList = ""
foreach var of varlist `varlist' {
if strpos("`var'", "`sub'") {
* gets the charcter just before sub to ensure it is not part of a vname
local charbefore = substr("`var'", strpos("`var'", "`sub'") - 1, 1 )
*di "the char that comes before sub is: `charbefore'"
if "`charbefore'" == "" | "`charbefore'" == "_" {
di "`var'"
local returnList `returnList' `var'
}
}
}
di "The list BEFORE returned is: `returnList'"
sreturn local `name' `returnList'
end
And finally... the testing code which fails both in command prompt or a do file:
* testing
Code:
ds
findVarsWithSubstring `r(varlist)', sub("d_") name(result)
di "The list returned is: `result'"

Comment