Reputation: 21
I have this below code:
$cmd = system ("p4 change -o 3456789");
I want to print the output -description of the change list - into a file.
$cmd = system ("p4 change -o 3456789 > output_cl.txt");
will write the output in to output_cl.txt
file.
But, is there anyway to get the output through $cmd
?
open(OUTPUT, ">$output_cl.txt") || die "Wrong Filename";
print OUTPUT ("$cmd");
will write 0 or 1 to the file. How to get the output from $cmd
?
Upvotes: 2
Views: 1064
Reputation: 29844
You can always use the following process to dump output straight to a file.
1) dup the system STDOUT
file descriptor, 2) open STDOUT
, 3) system, 4) copy the IO slot back into 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
But qx//
is probably what you're looking for.
reference: perlopentut
Of course this could be generalized:
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;
}
Upvotes: 1
Reputation: 139431
In addition to grabbing the entire output of a command with qx//
or backticks, you can get a handle on a command's output. For example
open my $p4, "-|", "p4 change -o 3456789"
or die "$0: open p4: $!";
Now you can read $p4
a line at a time and possibly manipulate it as in
while (<$p4>) {
print OUTPUT lc($_); # no shouting please!
}
Upvotes: 2
Reputation: 53966
If you find it confusing remembering what you need to run in order to get a command's return value, vs. its output, or how to handle different return codes, or forget to right-shift the resulting code, you need IPC::System::Simple, which makes all this, well, simple:
use IPC::System::Simple qw(system systemx capture capturex);
my $change_num = 3456789;
my $output = capture(qw(p4 change -o), $change_num);
Upvotes: 1