Why does "$v = @ARGV[0]" work ?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I've taken over some perl code that starts out with :

$v = @ARGV[0]

That's an @ sign on ARGV, not a dollar sign.

This seems to get the first element OK, but I don' know why. I've
never seen this construct used before, and I cannot find a parser rule
that says that you could use EITHER a $ or @ in this context.

Am curious to know why the result of this parse gets the same action
as taking the scalar with

$v = $ARGV[0]

Re: Why does "$v = @ARGV[0]" work ?

rlf wrote:
Quoted text here. Click to load it

@ARGV[0] is a one-element slice out of the @ARGV array, which is then
used as a list constructor for the assignment.  Now, man perldata says
that "[in] a context not requiring a list value, the value of what
appears to be a list literal is simply the value of the final element",
working the same as C's and Perl's comma operator.  More generally,
evaluating a list constructor in scalar context yields you that
last-element behavior, while evaluating a list VARIABLE in scalar
context gets you the length of the list.

Since the assignment is in scalar context, you get the last element of
the list constructor.  For example:

@list = ('foo', 'bar', 'krunk', 'quux') ;
$a = $list[0] ;        # sets $a to 'foo' as expected
$b = @list[0] ;        # slices ('foo') out of @list and
            # assigns last element to $b
$c = @list[2] ;        # sets $c to 'krunk'

... which then leads to ...

@d = @list[1,3] ;    # sets @d to ('bar', 'krunk', 'quux')
$e = @list[1,3] ;    # sets $e to 'quux'


Re: Why does "$v = @ARGV[0]" work ?

Quoted text here. Click to load it

It's worth noting that 'use warnings' will warn about this. If you have
inherited some code with dodgy coding standards, my recommendation would
be to start by adding

    use strict;
    use warnings;

at the top and fixing all the resultant diagnostics.

Quoted text here. Click to load it

An array. The difference between list and array is important.

Quoted text here. Click to load it


Re: Why does "$v = @ARGV[0]" work ?

Quoted text here. Click to load it

Thank you all for the clarification.

Site Timeline