tags:

views:

60

answers:

4

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?

+2  A: 

To store the output of your p4 command into an array, use qx:

my @lines = qx(p4 change -o 3456789);
toolic
+1  A: 

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;
}
Axeman
+1  A: 

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);
Ether
+1  A: 

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!
}
Greg Bacon