我有以下代码:
$cmd = system ("p4 change -o 3456789");
我想将更改列表的输出描述打印到文件中。
$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
获取输出?
答案 0 :(得分:2)
要将p4
命令的输出存储到数组中,请使用qx:
my @lines = qx(p4 change -o 3456789);
答案 1 :(得分: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!
}
答案 2 :(得分:1)
您始终可以使用以下过程将输出直接转储到文件中。
1) dup 系统STDOUT
文件描述符,2)open STDOUT
,3)系统,4)将IO插槽复制回STDOUT
:< / p>
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;
}
答案 3 :(得分:1)
如果你发现为了获得一个命令的返回值,它的输出,或者如何处理不同的返回代码,或者忘记右移生成的代码,你需要记住你需要运行的东西,你需要{{} 3}},这使得所有这些,简单,简单:
use IPC::System::Simple qw(system systemx capture capturex);
my $change_num = 3456789;
my $output = capture(qw(p4 change -o), $change_num);