如何在用于打开的命令中使用变量以及(-|)
管道输出,其中文件名被解释为通过管道输出给我们的命令。
$cmd = 'ps -elf';
open( my $fh, "-|",$cmd ) || die( "$cmd failed: $! " );
在这里,我想将在$cmd = 'ps $myOptions';
哪里$myOptions
设置为所需的选项,例如
$myOptions = "-elf"
如何才能做到这一点?
您可以为此使用字符串连接作为 $cmd = "ps ".$myOptions;
双引号对我有用:
#!/usr/bin/perl
use strict;
use warnings;
my $cmd = 'ps';
my $opt = "-elf";
open( my $fh, "-|", "$cmd $opt" ) || die( "$cmd failed: $! " );
while( <$fh>) { print "line $.: $_"; }
也可以:"ps $opt"
, join( ' ', $cmd, $opt) ,
$cmd 。' ' 。$opt and probably many other ways. You just have to make sure that the 3rd argument to open is a string, with the proper content
ps -elf`。为此,您必须确保插入变量(即没有单引号),并且不会以列表而不是字符串结束(即在双引号之间连接或使用变量)。
如果您想将命令指定为单个字符串(例如,如果您的选项实际上可能包含多个参数):
my $cmd = "ps $myOptions";
open my $fh, "$cmd |" or die "$cmd failed: $!";
如果要将其指定为两个字符串(例如,$myOptions
应始终将 if 视为单个参数):
open my $fh, "-|", "ps", $myOptions or die "ps $myOptions failed: $!";