1

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?

0

2 Answers 2

6

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 (i.e. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Running java calling perl script on a windows machine: process = r.exec("cmd /c perl D:\\perlexamples\\hello.pl");\
2
$javaoutput = `java javaprogram`;
or
system "java javaprogram";

For a jar file

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

3 Comments

Thank you for the fast reply;
Thank you for the fast reply, now i/m getting: Error: Could not find or load main class dbtools.jar
You probably need to set the classpath. Try to run the java program outside first and then use the same syntax inside.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.