我可以使用另一个 Perl 脚本中间的系统调用从 Perl 脚本获取值吗?
我正在尝试修改其他人编写的脚本,并且希望将我的脚本与他的脚本分开。
我编写的脚本以 print
行结尾,该行输出以空格分隔的所有相关数据。
例如: print "$sap $stuff $more_stuff";
我想在另一个 perl 脚本中间使用这些数据,并且我不确定是否可以对我编写的脚本使用系统调用。
例如: system("./sap_calc.pl $id"); #在这里从 sap_calc.pl 获取打印数据
这可以做到吗?如果没有,我该怎么办?
Somewhat related, but not using
system()
:I'm trying to modify a script that someone else has written and I wanted to keep my script separate from his.
The script I wrote ends with a print
line that outputs all relevant data separated by spaces.
Ex: print "$sap $stuff $more_stuff";
I want to use this data in the middle of another perl script and I'm not sure if it's possible using a system call to the script I wrote.
Ex: system("./sap_calc.pl $id"); #obtain printed data from sap_calc.pl here
Can this be done? If not, how should I go about this?
Somewhat related, but not using
system()
:How can I get one Perl script to see variables in another Perl script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找“反引号运算符”。
看看
perlop
,部分“类似引号的运算符”。一般来说,捕获程序的输出是这样的:
请注意反引号运算符仅捕获 STDOUT。因此,为了捕获所有内容(也包括 STDERR),命令需要附加常用的 shell 重定向“
2>&1
”。You're looking for the "backtick operator."
Have a look at
perlop
, Section "Quote-like operators".Generally, capturing a program's output goes like this:
Mind that the backtick operator captures STDOUT only. So in order to capture everything (STDERR, too) the commands needs to be appended with the usual shell redirection "
2>&1
".如果您想使用从其他脚本打印到标准输出的数据,则需要使用 反引号或
qx()
。system
只会返回 shell 命令的返回值,不是实际的输出。尽管执行此操作的正确方法是将实际代码导入到其他脚本中,但可以通过构建 module,或者简单地使用
do
。作为一般规则,最好使用所有 Perl 解决方案,而不是依赖系统/shell 作为“简化”的方式。
myfile.pl:
main.pl:
If you want to use the data printed to stdout from the other script, you'd need to use backticks or
qx()
.system
will only return the return value of the shell command, not the actual output.Although the proper way to do this would be to import the actual code into your other script, by building a module, or simply by using
do
.As a general rule, it is better to use all perl solutions, than relying on system/shell as a way of "simplifying".
myfile.pl:
main.pl:
perldoc perlipc
反引号,就像在 shell 中一样,将产生命令的标准输出作为字符串(或数组,取决于上下文)。它们可以更清楚地写成类似引号的
qx
运算符。open
还可以用于流式传输,而不是一次性读入内存(如qx
那样)。这还可以绕过 shell,从而避免各种引用问题。perldoc perlipc
Backquotes, like in shell, will yield the standard output of the command as a string (or array, depending on context). They can more clearly be written as the quote-like
qx
operator.open
can also be used for streaming instead of reading into memory all at once (asqx
does). This can also bypass the shell, which avoids all sorts of quoting issues.