Saravana Saravana - 22 days ago 6
Perl Question

stream Java STDOUT to perl STDOUT

I am running a java application from perl

here is the script

#!/usr/bin/perl
use strict;
use warnings;

$| = 1;

my $args = join (" " , @ARGV);

my $command = "/usr/java/jdk6/bin/java -jar runner-0.0.1-SNAPSHOT.jar $args";
print "Executing $command\n";
print "Please wait...\n";

print `$command`;


Java application writes debug info in the console[STDOUT] if run the command outside i.e. bash , but when I invoke from perl it buffers the debug messages and prints only on completion of the java application.

How to stream the debug messages when invoked from perl ?

I disbaled console buffer
$| = 1
but again same

Answer

Open it as a filehandle, and read from it the usual way.

#!/usr/bin/env perl
use strict;  
use warnings;

$| = 1;

my $command = "/usr/java/jdk6/bin/java -jar  runner-0.0.1-SNAPSHOT.jar @ARGV";
open ( my $java_output, '|-', $command ); 

while ( my $line = <$java_output> ) {
    print $line; 
}
close ( $java_output ); 

You might find IO::Select useful, if you want to do nonblocking reads of the output data too.

Comments