Different behavior of script in file vs -e

Discussion in 'Perl Misc' started by usenet, Jan 16, 2006.

  1. usenet

    usenet Guest

    Kindly consider this simple script:

    #!/usr/bin/perl -w
    @x = qw/foo bar baz/;
    print qq{$x[1]\n}

    Which prints "bar\n" (as expected).

    AFAIK, this should be the same thing as doing it this way:

    perl -we "@x = qw/foo bar baz/; print qq{$x[1]\n}"

    but the second case doesn't see $x[1] as a value of an array (it sees
    $x as an independent - and undef - scalar and '[1]' as a string literal
    - which, of course, generates a warning that "main::x" is used only

    What am I missing here???

    usenet, Jan 16, 2006
    1. Advertisements

  2. usenet

    usenet Guest

    Ha! I just saw where Paul Lalli posted a reply to a completely
    different question in a completely different newsgroup
    (http://tinyurl.com/ap7lc) which just happens to exactly answer my
    question as well.

    When I typed:
    the shell interprets $x before Perl ever gets to see it.

    Paul points out this problem can be avoided by escaping the dollar-sign
    or single-quoting the Perl expression.
    usenet, Jan 16, 2006
    1. Advertisements

  3. usenet

    Paul Lalli Guest

    The fact that $ is also the way your shell identifies variables.
    Before the above command, try doing:
    export x=shell_var
    and see what happens.

    To work around, either escape the $, or use ' instead of " to surround
    your Perl code.

    Paul Lalli
    Paul Lalli, Jan 16, 2006

  4. Try looking at what perl will be seeing:

    echo "@x = qw/foo bar baz/; print qq{$x[1]\n}"

    It sees $x as a *shell* variable, not a Perl variable.

    Single quotes instead of double quotes for your argument in the shell?
    Tad McClellan, Jan 17, 2006
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.