Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the output from a Perl pipe as it becomes available?

Tags:

pipe

perl

The following code is working sort of fine:

open( PIPE, '-|', 'ant' );
for( <PIPE> ) {
    print;
}

However, it doesn't do what I want. Since the Ant build can take 5 minutes, I would like to see the output line by line. Instead, I'm getting the entire input at the end of the process.

Looking at it with the Perl debugger, Perl waits at the 'for' statement, until Ant terminates. Why is that?

like image 847
Uri Avatar asked May 23 '10 20:05

Uri


1 Answers

Just for completeness (problem was solved as pointed out in the comment to Uri's answer) the problem arose because the for expression evaluates the <> operator in list context (see), equivalently to the following:

foreach $line (@lines = <PIPE>) {
    print $line;
}

In list context, the <> operator tries to read all lines from its input to asign to the list - and the input comes from a process, it will block until the process ends. Only afterwards it it will enter the loop body.

The alternative syntax

while( <PIPE> ) {           
    print; 
} 

is equivalent instead to

while(  $line = <PIPE> ) {
    print $line;
}

i.e., it consumes each line from the input in each loop iteration, and this is what one wants to do in this scenario.

like image 160
leonbloy Avatar answered Nov 08 '22 13:11

leonbloy