http://www.perlmonks.org?node_id=1012717

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

I need to have access to individual elements of the ARGV array in an online Perl command. Apparently, I have come to getting the whole array as follows:
$ perl -e "print @ARGV;" ONE- TWO- ONE-TWO-$
However, when I try to print just a single element, a weird output is what I get!
$ perl -e "print $ARGV[1];" ONE- TWO- ARRAY(0x92007ec)$
Is there something I'm missing?

Thanks,

Replies are listed 'Best First'.
Re: ARGV and online Perl commands
by toolic (Bishop) on Jan 10, 2013 at 19:32 UTC
    Here's what I get at my unix prompt:
    perl -e "print $ARGV[1];" ONE- TWO- ARGV: Undefined variable.

    But, if I change to single quotes to make my shell happy:

    perl -e 'print $ARGV[1];' ONE- TWO- TWO-

    UPDATE: when I switch my shell from tcsh to bash, I can duplicate your result.

Re: ARGV and online Perl commands
by blahblahblah (Priest) on Jan 10, 2013 at 20:07 UTC
    The shell is evaluating "$ARGV", which comes out as an empty string. Effectively, it is just like running the following:
    $ perl -e "print [1];" ONE- TWO- ARRAY(0x7fd5ea803ed0)$
    As toolic pointed out, one way to prevent the shell from evaluating $ARGV is by using single quotes around your command.

    tiny update: cleaned up the prompt, in order to simplify my example.
Re: ARGV and online Perl commands
by 2teez (Vicar) on Jan 10, 2013 at 21:30 UTC

    "...Is there something I'm missing? .."

    Previous comments are true, when you are on UNIX systems, but reverse is the case on Win systems.
    This example perl -e "print $ARGV[1];" ONE- TWO- ## prints TWO- works as expected on Win system. But with single-quotes, you get this error message: Can't find string terminator "'" anywhere before EOF at -e line 1.

    In fact, perlrun has this to say: ...On some systems, you may have to change single-quotes to double ones, which you must not do on Unix or Plan 9 systems...

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me
Re: ARGV and online Perl commands
by Anonymous Monk on Jan 11, 2013 at 02:42 UTC