Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I run a program and capture its output?

Little tricks

How do I run a program and capture its output?

by  MikeLacey  Posted    (Edited  )
Please browse through FAQ219-2884 and FAQ219-2889 first. Comments on this FAQ and the General FAQ's are very welcome.

There are a couple of ways this can be done, which way you choose is generally a matter of personal choice. You can't however, do it like this: (for the Windows guys, 'ls -l' is the same as 'dir /w')

@ls_output = system('ls -l');

This doesn't work because system() gives you the return code of the command rather than its output.

First Way
If you want the output of a command put into an array, do it like this:
Code:
@ls_output = `ls -l`;
You can the process the output of the command by looping through the @ls_output array.

If you need to capture the error output of a command do it like this:
Code:
@ls_output = `ls -l 2>&1`;
This code redirects the output of file-handle 2 (STDERR) to file-handle 1 (STDOUT). You can use this trick in Windows as well, Perl understands the system you're running on and will make it work for you.

Second Way
If you want to process the output of a command line by line as the command is running, do it like this:
Code:
$ls_cmd = 'ls -l';
open(LS_CMD, "$ls_cmd |") or die "Can't run '$ls_cmd'\n$!\n";
$i=0;
while(<LS_CMD>){ # each line of output is put into $_
# this bit just illustrates how each line of output might be processed
[tab]next if /^total/; # because we're only interested in real output
[tab]$ls_output[$i++] = $_; # save output line in the array
}

Again, if you need to capture the error output of a command do it like this:
Code:
$ls_cmd = 'ls -l 2>&1';
Used like this it will redirect the output of file-handle 2 (STDERR) to file-handle 1 (STDOUT). You can use this trick in Windows as well, Perl understands the system you're running on and will make it work for you.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top