in reply to Re: $ variables in command line
in thread $ variables in command line

Thanks,

but the problem actually lies deeper in my script, for example :

$test = "hello";
$s = "(hello)";
$r = "$1 world";
$test =~ s/$s/$r/;
print $test;


output : hello and not hello world as I would expect.

Is there any way I could do this ?

Replies are listed 'Best First'.
Re: Re: Re: $ variables in command line
by kvale (Monsignor) on Jun 26, 2002 at 21:44 UTC
    Similar problem, different context. In perl, double quotes causes interpolation, so in
    $r = "$1 world";
    $1 is substituted with whatever was matched in a previous regex. To prevent interpolation, use single quotes.

    That doesn't solve the whole problem, however. Now we need to substitute the strings, including metacharacters, into s///. To interpolate, then substitute, I'll use an eval:
    $s = '(hello)'; $r = '$1 world'; $_ = 'hello'; eval "s/$s/$r/"; print $_;
    A good general rule to follow is to use single quotes if you want the string as is, and use double quotes if you want interpolation.

    -Mark
      Thanks, it was the eval function that does the trick. Believe me, I have tried quotes, double quotes and everything that goes along with it many times before posting my question here but it never seemed to do what I wanted.

      Thanks again !

      Cheers,
      Mario.
Re^3: $ variables in command line
by tadman (Prior) on Jun 26, 2002 at 21:45 UTC
    You're asking for it to interpolate $1 in $r when you use double-quotes. Don't do this. $1 is undef when you do that, so of course, $r ends up being " world".

    Here's a really crazy example of how to do what you want.
    $test = "hello"; $s = "(hello)"; $r = '"$1 world"'; $test =~ s/$s/eval $r/e; print $test;
    Note that this uses eval, which isn't everyone's thing.