Running a Perl script within a Stata .do file

半腔热情 提交于 2020-01-05 00:44:50

问题


Is it possible to execute a Perl script within a Stata .do file?

I have a Stata .do file in which I make some manipulations to the data set and arrange it in a certain way. Then I have a Perl script in which I take one of the variables at this point, apply a Perl package to it, and make a transformation to one of the variables. In particular, I use Perl's NYSIIS function, resulting in a very short script. After this output is provided in Perl, I'd like to continue with some additional work in Stata.

Two alternatives that come to mind but that are less desirable are:

  1. Write Stata code to do nysiis but I prefer to use Perl's built-in function.

  2. outsheet and save the output from the Stata .do file as a .txt for Perl. Then do the Perl script separately to get another .txt. Then read in that .txt to Stata to a new .do file and resume.


回答1:


Your approach number 2 is what I use to call other programs to operate on Stata data. As Nick says, Stata won't necessarily wait for your output, unless you ask it to. You first outsheet the text file, then call the Perl script from Stata using ! to run something on the command line. Finally, have Stata periodically check for the result file, using a while loop and the sleep command so Stata isn't constantly checking.

outsheet using "perl_input.txt"
!perl my_perl_script.pl

while (1) {
    capture insheet using "perl_output.txt", clear
    if _rc == 0 continue, break
    sleep 10000
}

!rm perl_output.txt

Here, your formatted data is saved from Stata as perl_input.txt. Next, your Perl script is run from the command line, and using a while loop, Stata checks for the output every 10 seconds (sleep takes arguments in milliseconds). When it finds the output file, it breaks out of the while loop. The last line is a good idea so that when you re-use the code you don't run the risk of using the Perl output from the last run.




回答2:


I think the main issue is that although you can use the shell to call up something else, Stata is not going to wait for the results.

Start with help shell to see what is possible, but your #2 does sound easiest.



来源:https://stackoverflow.com/questions/16964084/running-a-perl-script-within-a-stata-do-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!