0

I am writing a little tool that needs to invoke a Perl script to do some stuff.

I already know and written the code on how to call it, but I have to provide the full-qualified path to the Perl script for the exec().

Is there any possibility to provide that script as a sort of package that can be invoked directly?

I want to generate an executable JAR later and want to also have the whole tool to provide the Perl script and not to know where it is located.

Currently its like:

private void extractAudioStream() {
    inputFile = "C:\\Users\\Stefan\\Documents\\temp_tshark\\forward_stream.pcap";
    outputFile_audiostream = "C:\\Users\\Stefan\\Documents\\temp_tshark\\forward_stream.pcm";

    String perl_cmd = "perl C:\\Users\\Stefan\\Documents\\tshark_bin\\rtp_dump.pl " + inputFile + " " + outputFile_audiostream;

    try {
        p = Runtime.getRuntime().exec(perl_cmd);

Hope question is clear enough.

I think this may not be as easy because the system perl command awaits the full-qualified path? Is there then any possibility to detect my current location and pass it to my cmd-String?

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Stefan
  • 2,603
  • 2
  • 33
  • 62

3 Answers3

2
String perl_cmd = "perl -e \"print \\\"bla\\n\\\";\";"
Runtime.getRuntime().exec(perl_cmd);

Edit: I forgot to put a space between -e and the script; you also have to escape backslashes and double-quotes in your script (twice if you're the script inline in Java instead of reading it from a jar file), which makes things a little awkward for more than one-liners.

So it would probably be better to use Process.getOutputStream to write the script to the Perl interpreter's standard input:

  String perlScript = "print \"hello\";"; // get from a jar with Class.getResourceAsStream()
  Process p = new ProcessBuilder("perl").redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.INHERIT).start();
  BufferedWriter w = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
  w.write(perlScript);
  w.close();
  p.waitFor();
Dan Berindei
  • 7,054
  • 3
  • 41
  • 48
  • if I run that command locally from my commandline, it's not executed. Furtheron it says from help: -e program one line of program (several -e's allowed, omit programfile) But its not just one line, its a whole script! – Stefan Apr 10 '12 at 09:17
1

if you read/store your perl script in a string, you can execute it like this:

perlScript = "print \"HELLO\\n\"; print \"CIAOOOO\\n\";";
String perl_cmd = "echo \"" + perlScript + "\" |perl";
Runtime.getRuntime().exec(perl_cmd);

Hope it helps...

sergio
  • 68,819
  • 11
  • 102
  • 123
0

You can write the script out to a file, say a temporary file, and execute it from there, then delete it when you're done.

Will Hartung
  • 115,893
  • 19
  • 128
  • 203