2010-08-04 28 views
2

输出我有这样的代码如下:

$cmd = system ("p4 change -o 3456789"); 

我想打印的变化列表的输出-description - 到一个文件中。

$cmd = system ("p4 change -o 3456789 > output_cl.txt"); 

会将输出写入到output_cl.txt文件中。

但是,有无论如何通过$cmd得到输出?

open(OUTPUT, ">$output_cl.txt") || die "Wrong Filename"; 
print OUTPUT ("$cmd"); 

会将0或1写入文件。如何从$cmd获得输出?

+2

你的问题是混乱的。你想要输出原始命令“p4 change -o 3456789”吗?还是想要别的东西?如果你想要原始命令的输出,不要使用'system'。相反,使用反引号。 – sholsapp 2010-08-04 18:42:10

回答

2

要将p4命令的输出存入一个数组,使用qx

my @lines = qx(p4 change -o 3456789); 
1

您可以随时使用以下过程来转储直接输出到文件中。

1)DUP系统STDOUT文件描述符,2)open STDOUT,3)系统,4)复制IO插槽回STDOUT

open(my $save_stdout, '>&1');    # dup the file 
open(STDOUT, '>', '/path/to/output/glop'); # open STDOUT 
system(qw<cmd.exe /C dir>);    # system (on windows) 
*::STDOUT = $save_stdout;     # overwrite STDOUT{IO} 
print "Back to STDOUT!";      # this should show up in output 

qx//可能是你在找什么。

参考:perlopentut


当然,这可以概括:

sub command_to_file { 
    my $arg = shift; 
    my ($command, $rdir, $file) = $arg =~ /(.*?)\s*(>{1,2})\s*([^>]+)$/; 
    unless ($command) { 
     $command = $arg; 
     $arg  = shift; 
     ($rdir, $file) = $arg =~ /\s*(>{1,2})\s*([^>]*)$/; 
     if (!$rdir) { 
      ($rdir, $file) = ('>', $arg); 
     } 
     elsif (!$file) { 
      $file = shift; 
     } 
    } 
    open(my $save_stdout, '>&1'); 
    open(STDOUT, $rdir, $file); 
    print $command, "\n\n"; 
    system(split /\s+/, $command); 
    *::STDOUT = $save_stdout; 
    return; 
} 
1

如果你觉得困惑记住,你需要为了得到一个命令的返回值运行什么,对它的输出,或者如何处理不同的返回码,或者忘记将结果码右移,你需要IPC::System::Simple,这使得所有这些都很简单:

use IPC::System::Simple qw(system systemx capture capturex); 

my $change_num = 3456789; 
my $output = capture(qw(p4 change -o), $change_num); 
2

除了用qx// or backticks抓取命令的全部输出外,还可以获得命令输出的句柄。例如

open my $p4, "-|", "p4 change -o 3456789" 
    or die "$0: open p4: $!"; 

现在你可以一次读取$p4一条线,可能操纵它作为

while (<$p4>) { 
    print OUTPUT lc($_); # no shouting please! 
}