程序中如何使用语法?

How is syntax used in a program?

我已经在 Stata 中多次使用 program 命令了。

今天,我正在尝试自学如何创建一个使用输入的程序。我已经尝试查看 syntax 帮助文件和 these lecture slides I found on the internet 的第 71 页,但我不知道如何执行此操作。

如果您能向我展示一些全面涵盖该特定主题的文档,我将不胜感激。或者在下面指出我做错了什么。

如您所见,我只想创建一个小程序来检查指定文件夹中是否存在文件 (capture confirm file),但如果有,我想显示我自己的对话框错误 (window stopbox note),如果是,则按顺序退出 do 文件 (exit 601)。

cap program drop checkfile
program checkfile
syntax varlist, folder(varname) file(varname)
capture confirm file "`folder'/`file'"
    if _rc == 601 {
        window stopbox note `"`file' is not in `folder'"' // creates a dialogue box for the error
        exit 601
    }
end

checkfile folder(C:\Users\User\Documents) file(NIDSw5.dta)

Returns错误:

factor-variable and time-series operators not allowed
r(101);

我不确定如何使用 syntax 来获取文件夹路径和文件名。请注意,这些通常是字符串,但我猜是:

"`folder'/`file'"

将导致,例如,如果输入带有引号,则 ""C:\Users\User\Documents"/"NIDSw5.dta"",所以这就是为什么我认为我应该使用 local(input) 方法。

另请注意,我将使用全局变量 ($DataIN) 而不是将文件夹路径字符串放在那里,并且文件名包含附加到字符串上的全局变量。

删除 varlist, 导致错误:

invalid syntax
r(197);

以下对我有用:

program checkfile
syntax, folder(string) file(string)
capture confirm file "`folder'/`file'"
if _rc == 601 {
    window stopbox note `"`file' is not in `folder'"' 
    exit 601
}
end

然后您只需输入:

checkfile, folder(C:\Users\User\Documents) file(NIDSw5.dta)

编辑:

您也可以不使用以下选项来完成此操作:

program checkfile
capture confirm file "`1'/`2'"
if _rc == 601 {
    window stopbox note `"`2' is not in `1'"'
    exit 601
}
end

checkfile C:\Users\User\Documents NIDSw5.dta