in reply to Re: use of parentheses around a variable
in thread use of parentheses around a variable

"my ($var) is a list (of one scalar) equivalent to (my $var)"

declear:
(my $var1, $var2, $var3)

you cannot access the list, only the scalar variables, right?
  • Comment on Re^2: use of parentheses around a variable

Replies are listed 'Best First'.
Re^3: use of parentheses around a variable
by ikegami (Patriarch) on Jun 24, 2008 at 06:20 UTC

    First, keep in mind that
    (my $var1, $var2, $var3)
    is different than
    my ($var1, $var2, $var3)
    and
    (my $var1, my $var2, my $var3)
    The first only declares one variable but the other two declare three.

    >perl -Mstrict -e"my ($x, $y)" >perl -Mstrict -e"(my $x, my $y)" >perl -Mstrict -e"(my $x, $y)" Global symbol "$y" requires explicit package name at -e line 1. Execution of -e aborted due to compilation errors.

    Now on to your question. What good is making a construct you can't access? That would be quite counter-productive. Either I don't know what you mean by "access", or the answer is "Of course you can access a list".

Re^3: use of parentheses around a variable
by massa (Hermit) on Jun 24, 2008 at 10:32 UTC
    • (my $var) is a list with one scalar called $var, and introduces $var to the current scope context.
    • my ($v1, $v2) is a list with two scalars ($v1, $v2) and introduces both to the current scope context.
    • (my $v1, $v2) is a list with two scalars, but only introduces $v1 to the current scope context, meaning that if use strict is in effect, $v2 should be already introduced in the context or an error will occur.
    • When there is a list on the left-hand-side of an assignment, it forces list context to the right-hand-side (IOW, the right-hand-side will be interpreted as a list), so, my ($v) = @_ reads the first element of @_ and put it in $v.
    • When there is a scalar on the left-hand-side of an assignment, it forces scalar context to the right-hand-side (forces it to be interpreted as a scalar, pretty much as if you had put the word scalar in front of it), so, my $v = @_ is the same as my $v = scalar @_ and, because an array in scalar context is the number of its elements, this puts the number of elements of @_ in $v.
    Simple, no? :-)