×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

Little tricks

How do I run a program and capture its output? by MikeLacey
Posted: 11 Jun 04 (Edited 14 Jul 05)

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
    next if /^total/; # because we're only interested in real output
    $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.

Back to Perl FAQ Index
Back to Perl Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close