in reply to use of parentheses around a variable

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

The context of the RHS of an assignment operator is determined by the LHS of the operator.

An array in scalar context evaluates to the number of elements in the array.
An array in list context evaluates to a list of its elements.

For example,

sub test { my $var1 = @_; my ($var2) = @_; (my $var3) = @_; my ($var4, $var5) = @_; (my $var6, my $var7) = @_; print("my \$var1 = \@_; -> $var1\n"); print("my (\$var2) = \@_; -> $var2\n"); print("(my \$var3) = \@_; -> $var3\n"); print("my (\$var4, \$var5) = \@_; -> $var4, $var5\n"); print("(my \$var6, my \$var7) = \@_; -> $var6, $var7\n"); } test('abc', 'def');
my $var1 = @_; -> 2 my ($var2) = @_; -> abc (my $var3) = @_; -> abc my ($var4, $var5) = @_; -> abc, def (my $var6, my $var7) = @_; -> abc, def

Replies are listed 'Best First'.
Re^2: use of parentheses around a variable
by perlfan99 (Sexton) on Jun 24, 2008 at 06:01 UTC
    "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?

      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".

      • (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? :-)