如何在Perl脚本中调用Shell命令?

问题描述:

如何举例说明如何调用Shell命令(在Perl脚本中说"ls -a")以及检索命令输出的方式?

What would be an example of how I can call a shell command, say 'ls -a' in a Perl script and the way to retrieve the output of the command as well?

如何运行Shell脚本来自Perl程序

1.使用系统system($command, @arguments);

1. Using system system($command, @arguments);

例如:

system("sh", "script.sh", "--help" );

system("sh script.sh --help");

系统将使用以下命令执行$命令 @arguments并在完成后返回您的脚本.您可以检查$! 对于由外部应用程序传递给OS的某些错误.读 系统文件的细微差别 调用略有不同.

System will execute the $command with @arguments and return to your script when finished. You may check $! for certain errors passed to the OS by the external application. Read the documentation for system for the nuances of how various invocations are slightly different.

2.使用exec

2. Using exec

这与系统的使用非常相似,但是它将 在执行时终止脚本.再次,阅读文档 有关 exec 的更多信息.

This is very similar to the use of system, but it will terminate your script upon execution. Again, read the documentation for exec for more.

3.使用反引号或qx//

3. Using backticks or qx//

my $output = `script.sh --option`;

my $output = qx/script.sh --option/;

反引号运算符及其等效的qx//,在运算符内部执行命令和选项,并在完成时将命令输出返回到STDOUT.

The backtick operator and it's equivalent qx//, excute the command and options inside the operator and return that commands output to STDOUT when it finishes.

还有一些方法可以通过创造性地使用 open 来运行外部应用程序,但是这是高级用途;阅读文档以了解更多信息.

There are also ways to run external applications through creative use of open, but this is advanced use; read the documentation for more.