SOConnell
SOConnell

Reputation: 793

Custom program - debugging syntax

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);

Upvotes: 2

Views: 155

Answers (1)

Nick Cox
Nick Cox

Reputation: 37208

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"

Upvotes: 3

Related Questions