john
john

Reputation: 179

Store executable jar output in a variable in Perl

I need the retrieve the output of a Java program and store it in a Perl variable so that i'll be able to use split function. I am getting the java output using,

my @args = ("java", "-jar", "first.jar");

system(@args);

But how to convert this @args into $args variable (string) so that i can split the output from the string.

Upvotes: 3

Views: 323

Answers (2)

mkHun
mkHun

Reputation: 5927

I hope you need to store the output of the jar file. So use backtick instead of system. Try to know difference between system and Backtick / qx

my @args = ("java", "-jar", "first.jar");

my $result = `@args`;

my @ans = split(" ",$result);

print "$ans[0] $ans[1]";

suppose your result is xyz abc. $ans[0] store the xyz and $ans[1] store the abc

Upvotes: 1

Sebastian
Sebastian

Reputation: 2550

I don't know why you want to convert the arguments, but it looks like it would be easy:

my $cmd = join(' ', @args);

But wait... what if you add an argument "firstname lastname"?

my @args = ("java", "-jar", "first.jar", "firstname lastname");
my $cmd = join(' ', @args);

The result would be:

java -jar first.jar firstname lastname

Your single name argument would become two. The correct form would be:

java -jar first.jar "firstname lastname"

map could help:

my $cmd = join(' ', map { "'$_'" } @args);

(Extra efforts are needed if your args (may) contain ' quotes.)

For capturing the output, use either backticks or open:

my $output = `$cmd`; # Multiline output in one variable
my @output = `$cmd`; # Each output line in one array element

# Read the output line by line saving memory
open my $fh,'-|',$cmd;
while (<$fh>) {
    # Do something with a single output line in $_
}

The last one doesn't need to parse the whole output into a single variable or array: It handles one line in each loop iteration. You could easily handle hundreds of GBs of output because only one line needs to be stored at a time.

Upvotes: 0

Related Questions