views:

59

answers:

2

Is there a filehandle/handle for the output of a system command I execute in Perl?

+1  A: 

Yes, you can use a pipe like this:

open(my $pipe, "ls|") or die "Cannot open process: $!";
while (<$pipe>) {
    print;
}

See the documentation for open for more information, and perlipc for a complete description of pipe operation.

Greg Hewgill
Two-arg `open` is old and crufty (and potentially dangerous). [Use the three-arg version instead](http://www.modernperlbooks.com/mt/2010/04/three-arg-open-migrating-to-modern-perl.html)
Daenyth
+8  A: 

Here's an example of establishing pipes between your script and other commands, using the 3-argument form of open:

open(my $incoming_pipe, '-|', 'ls -l')             or die $!;
open(my $outgoing_pipe, '|-', "grep -v '[02468]'") or die $!;

my @listing = <$incoming_pipe>;          # Lines from output of ls -l
print $outgoing_pipe "$_\n" for 1 .. 50; # 1 3 5 7 9 11 ...
FM