你混淆了两个不同的东西。首先,使用my声明多个变量时,需要使用括号:
my $foo, $bar;
不起作用,因为它被认为是两个不同的语句:
my $foo;
$bar;
因此,您需要括号将参数组合到 函数 my:
的参数列表中
my($foo, $bar);
其次,您有明确的分组以调用列表上下文:
$foo, $bar = "a", "b"; # wrong!
将被视为三个单独的语句:
$foo;
$bar = "a";
"b";
但是如果您使用括号将$foo 和$bar 组合成一个列表,则赋值运算符将使用列表上下文:
($foo, $bar) = ("a", "b");
奇怪的是,如果你去掉 RHS 括号,你也会遇到一个打嗝:
($foo, $bar) = "a", "b"; # Useless use of a constant (b) in void context
但这是因为= 运算符的优先级高于逗号,,您可以在perlop 中看到。如果你尝试:
my @array = ("a", "b");
($foo, $bar) = @array;
您将获得不带括号的所需行为。
现在完成循环,让我们删除上面的列表上下文,看看会发生什么:
my @array = ("a", "b");
$foo = @array;
print $foo;
这将打印2,因为数组是在标量上下文中计算的,而标量上下文中的数组返回它们包含的元素数。在这种情况下,它是2。
因此,诸如此类的语句使用列表上下文:
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
这是一种覆盖标量分配中隐含的标量上下文的方法。为了比较,这些分配是在标量上下文中:
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