philiotis has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I am calling perl from within Java using
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmdLine)

One of the arguments that I pass to perl is a quoted string (containing multiple words) that perl should accept as a single argument. The problem is that Perl breaks this string in to multiple arguments.

I have tried double quotes and single quotes.

I can run this on the command line without a problem it is only when i run it from within Java that the problem occurs.
Here is an example of the command
/usr/bin/perl myperlScript.pl argument1 "this is a test"

Perl interprets this as
ARGV 0 argument1
ARGV 1 this
ARGV 2 is
ARGV 3 a
ARGV 4 test

what I would like it to be is
ARGV 0 argument1
ARGV 1 this is a test

thanks

Replies are listed 'Best First'.
Re: ARGV issue.
by Errto (Vicar) on Jan 19, 2005 at 04:37 UTC
    You should use the method
    public Process exec(String[] cmdarray) throws IOException
    instead of
    public Process exec(String command) throws IOException
    This will allow you to specify exactly what arguments you want to pass, spaces and all. Note that the issue here is entirely with Java, and not at all with Perl.
Re: ARGV issue.
by BrowserUk (Patriarch) on Jan 19, 2005 at 00:24 UTC

    A pure guess, but it is probably the java rt.exec call that is striping the quotes before they make it to the perl program. You could try escaping them (with backslashes?) before your make the call.


    Examine what is said, not who speaks.
    Silence betokens consent.
    Love the truth but pardon error.
      Hi BrowserUk I thought so too at first but that is not the issue. I tried it and my first argument became "This and the last one was test"

        The point is, that between where you specify the command string and where Perl is receiving it, something is splitting the command on whitespace--and it's not Perl!

        Quick look at the Java docs shows that exec( String command ) uses StringTokenizer to do the splitting. As far as my quick look went it doesn't have a mechanism for escaping spaces, and from your test, it passes escape-quoted strings with the quotes intact. :(

        However, just below the form of exec that you are using, the docs describe another form: exec( String[] cmdarray ), which without trying to interpret the (Java) docs, sounds suspiciosly like Perl's list forms of exec and system whereby you pre-tokenize the arguments into the array, and they get passed uninterpreted.

        I suggest you pursue that course.

        (I don't like Java, but their documentation is both thorough and easy to use! Perl(6) could learn a thing or two there)


        Examine what is said, not who speaks.
        Silence betokens consent.
        Love the truth but pardon error.
Re: ARGV issue.
by Anonymous Monk on Jan 19, 2005 at 11:33 UTC