You are confusing two different things. First off, when using my
to declare several variables, you need to use parentheses:
my $foo, $bar;
Does not work, as it is considered to be two different statements:
my $foo;
$bar;
So you need parentheses to group together the argument into an argument list to the function my
:
my($foo, $bar);
Secondly, you have explicit grouping in order to invoke list context:
$foo, $bar = "a", "b"; # wrong!
Will be considered three separate statements:
$foo;
$bar = "a";
"b";
But if you use parentheses to group $foo
and $bar
into a list, the assignment operator will use a list context:
($foo, $bar) = ("a", "b");
Curiously, if you remove the RHS parentheses, you will also experience a hickup:
($foo, $bar) = "a", "b"; # Useless use of a constant (b) in void context
But that is because the =
operator has higher precedence than comma ,
, which you can see in perlop. If you try:
my @array = ("a", "b");
($foo, $bar) = @array;
You will get the desired behaviour without parentheses.
Now to complete the circle, lets remove the list context in the above and see what happens:
my @array = ("a", "b");
$foo = @array;
print $foo;
This prints 2
, because the array is evaluated in scalar context, and arrays in scalar context return the number of elements they contain. In this case, it is 2
.
Hence, statements such as these use list context:
my ($foo) = @array; # $foo is set to $array[0], first array element
my ($bar) = ("a", "b", "c"); # $bar is set to "a", first list element
It is a way of overriding the scalar context which is implied in scalar assignment. For comparison, these assignments are in scalar context:
my $foo = @array; # $foo is set to the number of elements in the array
my $bar = ("a", "b", "c"); # $bar is set to "c", last list element