简体   繁体   中英

How can I invoke a Java program from Perl?

I'm new with Perl and I'm trying to do something and can't find the answer.

I created a Java project that contains a main class that gets several input parameters.

I want to wrap my Java with Perl: I want to create a Perl script that gets the input parameters, and then passes them to the Java program, and runs it.

For example:

If my main is called mymain , and I call it like this: mymain 3 4 hi ( 3 , 4 and hi are the input parameters), I want to create a Perl program called myperl which when it is invoked as myperl 3 4 hi will pass the arguments to the Java program and run it.

How can I do that?

Running a Java program is just like running any other external program.

Your question has two parts :

  1. How do I get the arguments from Perl to the Java program?
  2. How do I run the program in Perl?

For (1) you can do something like

my $javaArgs = " -cp /path/to/classpath -Xmx256";
my $className = myJavaMainClass;
my $javaCmd = "java ". $javaArgs ." " . $className . " " . join(' ', @ARGV);

Notice the join() function - it will put all your arguments to the Perl program and separate them with space.

For (2) you can follow @AurA 's answer.

  • Using the system() function

     my $ret = system("$javaCmd"); 

This will not capture (ie put in the variable $ret ) the output of your command, just the return code, like 0 for success.

  • Using backticks

     my $out = `$javaCmd`; 

This will populate $out with the whole output of the Java program ( you may not want this ).

  • Using pipes

     open(FILE, "-|", "$javaCmd"); my @out = <FILE> 

This is more complicated but allows more operations on the output.

For more information on this see perldoc -f open .

$javaoutput = `java javaprogram`;
or
system "java javaprogram";

For a jar file

$javaoutput = `java -jar filename.jar`;
or
system "java -jar filename.jar";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM