2
votes

I have created the following program which is not playing well with string expressions. I haven't been able to figure out the right adjustment to add in my syntax definition to get this to work as intended.

I think this is something small, but I haven't been able to get it right yet. Or, references to something that would help would also be appreciated.

Included is the program and some dummy code that yields the same error.

Thanks!

cap program drop repl_conf
program define repl_conf
    syntax varlist =exp  [if] 
    qui count `if'
    if r(N) ==0 {
    di as err "NO MATCHES -- NO REPLACE"
    exit 9
    }
    else {
    noi dis "SUCCESSFUL REPLACE of >=1 OBS -- " r(N) " OBS replaced"
    qui replace `varlist' `exp' `if'
    }
end

sysuse auto, clear
repl_conf length=999 if length==233
repl_conf make="ZZZ" if make=="AMC Concord"
type mismatch
r(109);
1
I think exp here can only be an expression with numeric result. Your program does not pass the syntax statement when offered one with string result.Nick Cox
I guess you need to use gettoken to peel off the tokens in the command line one by one.Nick Cox
This seems like an unfortunate feature. replace and gen both work with a string or numeric exps, but they are both built-in commands.dimitriy

1 Answers

3
votes

This gets further. I moved the second message so that it is only issued if the replace was successful.

program define repl_conf
    gettoken varname 0 : 0, parse(=) 
    confirm var `varname' 
    gettoken eq 0 : 0, parse(=) 
    syntax anything [if] 
    qui count `if'
    if r(N) == 0 {
         di as err "NO MATCHES -- NO REPLACE"
         exit 9
    }
    else {
         qui replace `varname' = `anything' `if'
         noi di "SUCCESSFUL REPLACE of >=1 OBS -- " r(N) " OBS replaced"
    }
end

sysuse auto, clear
repl_conf length=999 if length==233
repl_conf make="ZZZ" if make=="AMC Concord"