如何在用于打开的命令中使用变量以及( - |)管道输出,其中文件名被解释为管道输出给我们的命令

时间:2012-08-30 03:52:33

标签: perl pipe

如何在用于打开的命令中使用变量以及(-|)管道输出,其中文件名被解释为管道输出给我们的命令。

$cmd = 'ps -elf';
open( my $fh, "-|",$cmd  ) || die( "$cmd failed: $! " );

我希望$cmd = 'ps $myOptions'; 其中$myOptions将被设置为所需的选项,例如 $myOptions = "-elf"

如何做到这一点?

3 个答案:

答案 0 :(得分:2)

您可以将字符串连接用作$ cmd =“ps”。$ myOptions;

答案 1 :(得分:1)

双重引用管道对我有用:

#!/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",加入('',$ 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`。为此,你必须确保插入变量(即没有单引号),并且你不会得到一个列表而不是一个字符串(即连接或在双引号之间使用变量)。

答案 2 :(得分:0)

如果要将命令指定为单个字符串(例如,如果您的选项实际上可能包含多个参数):

my $cmd = "ps $myOptions";
open my $fh, "$cmd |" or die "$cmd failed: $!";

如果要将其指定为两个字符串(例如,如果$myOptions应始终被视为单个参数):

open my $fh, "-|", "ps", $myOptions or die "ps $myOptions failed: $!";
相关问题