in reply to lines written to stdout by a backtick command

Here is a program that prints whatever you send in via the command line 10 times

#!/usr/bin/perl -w # Program: printsth print join (' ', @ARGV), $/ for (1..10);

Now I call this program inside another program and capture it's output

#!/usr/bin/perl -w # Program: captpipe my $arg = "hi there"; print ("Going to call another perl program and capture it's output\n") +; open (PIPE,"printsth $arg | ") or die $!; while (<PIPE>) { print; }

when you just run  printsth hi there you will get  hi there\n 10 times.

when you execute the captpipe script you will see the same output.

Output

[sk]% captpipe Going to call another perl program and capture it's output hi there hi there hi there hi there hi there hi there hi there hi there hi there hi there

this is a better way to capture output than using backticks!

Replies are listed 'Best First'.
Re^2: lines written to stdout by a backtick command
by oceanic (Novice) on Aug 15, 2005 at 07:26 UTC
    Yay! I used the open (PIPE,"blah") method and it worked!

    I had a feeling it was something to do with the depth and complexity of the piping and stdout reading that was causing it - using this different method must have corrected that.

    Thanks sk !

    Drew

      Yay! I used the open (PIPE,"blah") method and it worked!

      Seeing what you chose to omit in your shortened rendition of the method, I hope you realize that what matters here is not the name "PIPE" for the handle, but the | at the end of the second argument to open. I.e. it would have worked just as well if you had used

      open( THIS_IS_NOT_A_PIPE,"printsth $arg |" ) or die $!; while ( <THIS_IS_NOT_A_PIPE> ) { print; }
      (With apologies to Magritte.)

      the lowliest monk