一般来说,我使用system、open、IPC::Open2 或IPC::Open3,这取决于我想要做什么。 qx// 运算符虽然简单,但其功能过于受限,无法在快速破解之外非常有用。我发现open 更方便。
system:运行一个命令,等待它返回
当您想运行命令时使用system,不关心其输出,并且不希望 Perl 脚本在命令完成之前执行任何操作。
#doesn't spawn a shell, arguments are passed as they are
system("command", "arg1", "arg2", "arg3");
或
#spawns a shell, arguments are interpreted by the shell, use only if you
#want the shell to do globbing (e.g. *.txt) for you or you want to redirect
#output
system("command arg1 arg2 arg3");
当您想要运行命令、捕获它写入 STDOUT 的内容并且不希望 Perl 脚本在命令完成之前执行任何操作时,请使用 qx//。
#arguments are always processed by the shell
#in list context it returns the output as a list of lines
my @lines = qx/command arg1 arg2 arg3/;
#in scalar context it returns the output as one string
my $output = qx/command arg1 arg2 arg3/;
exec:用另一个进程替换当前进程。
当你想运行一个命令时使用exec 和fork,不关心它的输出,也不想等待它返回。 system 真的只是
sub my_system {
die "could not fork\n" unless defined(my $pid = fork);
return waitpid $pid, 0 if $pid; #parent waits for child
exec @_; #replace child with new process
}
您可能还想阅读waitpid 和perlipc 手册。
open: 运行一个进程并创建一个到它的 STDIN 或 STDERR 的管道
当您想将数据写入进程的 STDIN 或从进程的 STDOUT 读取数据(但不能同时)时,请使用 open。
#read from a gzip file as if it were a normal file
open my $read_fh, "-|", "gzip", "-d", $filename
or die "could not open $filename: $!";
#write to a gzip compressed file as if were a normal file
open my $write_fh, "|-", "gzip", $filename
or die "could not open $filename: $!";
IPC::Open2:运行一个进程并创建一个到 STDIN 和 STDOUT 的管道
当您需要读取和写入进程的 STDIN 和 STDOUT 时,请使用 IPC::Open2。
use IPC::Open2;
open2 my $out, my $in, "/usr/bin/bc"
or die "could not run bc";
print $in "5+6\n";
my $answer = <$out>;
IPC::Open3:运行一个进程并创建一个到 STDIN、STDOUT 和 STDERR 的管道
当您需要捕获进程的所有三个标准文件句柄时,请使用IPC::Open3。我会写一个例子,但它的工作方式与 IPC::Open2 的工作方式基本相同,但参数和第三个文件句柄的顺序略有不同。