6

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

T.Rob
  • 31,522
  • 9
  • 59
  • 103
syker
  • 10,912
  • 16
  • 56
  • 68

2 Answers2

12

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 ...
FMc
  • 41,963
  • 13
  • 79
  • 132
1

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
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 4
    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 Jul 14 '10 at 03:12