如何从 Perl 调用 Java 程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10631348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I invoke a Java program from Perl?
提问by Ben Hoffman
I'm new with Perl and I'm trying to do something and can't find the answer.
我是 Perl 的新手,我正在尝试做某事但找不到答案。
I created a Java project that contains a main class that gets several input parameters.
我创建了一个 Java 项目,其中包含一个获取多个输入参数的主类。
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.
我想用 Perl 包装我的 Java:我想创建一个 Perl 脚本来获取输入参数,然后将它们传递给 Java 程序并运行它。
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.
如果我的主叫mymain
,我这样称呼它:mymain 3 4 hi
(3
,4
并且hi
是输入参数),我想创建一个名为Perl程序myperl
,当它被援引为myperl 3 4 hi
将传递参数给Java程序并运行它。
How can I do that?
我怎样才能做到这一点?
回答by Chip
Running a Java program is just like running any other external program.
运行 Java 程序就像运行任何其他外部程序一样。
Your question has two parts :
你的问题有两部分:
- How do I get the arguments from Perl to the Java program?
- How do I run the program in Perl?
- 如何从 Perl 获取参数到 Java 程序?
- 我如何在 Perl 中运行程序?
For (1) you can do something like
对于(1)你可以做类似的事情
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.
注意这个join()
函数——它将把你所有的参数放到 Perl 程序中,并用空格分隔它们。
For (2) you can follow @AurA 's answer.
对于(2),您可以按照@AurA 的回答进行操作。
Using the
system()
functionmy $ret = system("$javaCmd");
使用
system()
功能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.
这不会捕获(即放入变量$ret
)您的命令的输出,只是返回代码,就像0
成功一样。
Using backticks
my $out = `$javaCmd`;
使用反引号
my $out = `$javaCmd`;
This will populate $out with the whole output of the Java program ( you may not want this ).
这将使用 Java 程序的整个输出填充 $out(您可能不想要这个)。
Using pipes
open(FILE, "-|", "$javaCmd"); my @out = <FILE>
使用管道
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.
有关这方面的更多信息,请参阅perldoc -f open。
回答by AurA
$javaoutput = `java javaprogram`;
or
system "java javaprogram";
For a jar file
对于 jar 文件
$javaoutput = `java -jar filename.jar`;
or
system "java -jar filename.jar";