2014-01-16 40 views
2

我創建了下列程序,它不能很好地與字符串表達式配合使用。我一直無法找出正確的調整來添加我的語法定義以使其按預期工作。自定義程序 - 調試語法

我覺得這個東西很小,但是我還沒有把它弄清楚。或者,引用一些有用的東西也將被讚賞。

包括程序和一些產生相同錯誤的虛擬代碼。

謝謝!

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

我認爲這裏的'exp'只能是一個帶數字結果的表達式。當提供一個字符串結果時,你的程序不會傳遞'syntax'語句。 –

+0

我想你需要使用'gettoken'來逐個剝離命令行中的令牌。 –

+0

這似乎是一個不幸的功能。 'replace'和'gen'都使用字符串或數字'exp's,但它們都是內置命令。 –

回答

3

這會更進一步。我移動了第二條消息,以便僅在replace成功時發出。

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" 
+0

非常感謝,@NickCox。這有效,並幫助我修復了後來遇到麻煩的'gettoken'語法。 – SOConnell