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

I am getting an error when passing $INVALID_STRING as a parameter to a java program which is executed through the back tick operator.
$INVALID_STRING="!"$\%&'()*/@`~"; $STRING_TO_EXECUTE="java myprogram -opt1 ABC -opt2 $INVALID_STRING"; @output=`$STRING_TO_EXECUTE 2>&1`;
On executing my Perl Script I get the following error:
sh: -c: line 1: unexpected EOF while looking for matching ``' sh: -c: line 3: syntax error: unexpected end of file
I tried removing the character ` and ' out of the $INVALID STRING, but it still complains with similar error. Can anyone help solve this problem ? Thanks in advance.

Replies are listed 'Best First'.
Re: Error using back tick operators if it has special perl chars in it
by japhy (Canon) on Jul 28, 2004 at 19:29 UTC
    First of all, the code you've given us shouldn't even compile as Perl. I would suggest the following:
    $INVALID_STRING = quotemeta q<!"$\%&'()*/@`~>; $STRING_TO_EXECUTE = "java myprogram -opt1 ABC -opt2 $INVALID_STRING";
    Or, better yet, use open() instead.
    _____________________________________________________
    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: Error using back tick operators if it has special perl chars in it
by gaal (Parson) on Jul 28, 2004 at 19:36 UTC
    Your problem is only partly that the string contains special Perl characters.

    1. When you assign to $INVALID_STRING, make sure you protect yourself from interpolation. '"!"' etc. just don't end up in your variable. In this case, you can use the generic single quote op q:

    $INVALID_STRING = q{!"$\%&'()*/@`~}; Here { ... } act as the delimiters, but many other options are available. See perlop for details.

    2. Your main problem is that the *shell* is having a hard time dealing with the string, not perl. This is your main problem because it's harder to solve :-)

    I'm afraid that this will depend a bit on which shell your system uses; experiment a bit with escaping ! and ' and putting everything in single quotes.

Re: Error using back tick operators if it has special perl chars in it
by revdiablo (Prior) on Jul 28, 2004 at 22:26 UTC

    To expand a bit on japhy's response, you will be best served by using a piping form of open, with the parameters in list form. Using list form will prevent any shell expansion on the parameters, which avoids many problems. Here's a very simple example:

    open my $lsfh, "-|", "ls", "-l" or die "Cannot open pipe from 'ls': $!"; while (<$lsfh>) { print; } close $lsfh;