好问题 - 这里有一些区别:
$a[0] = localtime; print @a; # this prints: Tue Nov 1 18:51:13 2011
@a[0] = localtime; print @a; # this prints the amount of seconds, e.g. 13
$a[0] = grep{}, qw(6 2 8); print @a; # this prints: 3
@a[0] = grep{}, qw(6 2 8); print @a; # this prints: 6
$a[0] = reverse ("a", "b"); print @a; # this prints: ba
@a[0] = reverse ("a", "b"); print @a; # this prints: b
$a[0] = ("a", "b"); print @a; # this prints: b
@a[0] = ("a", "b"); print @a; # this prints: a
切片是否为[1] 无关紧要。您可以通过查找在不同上下文中评估时给出不同结果的函数来创建更多示例。
后一个(第4个)例子的解释:
$a[0] 中的 $ 创建一个标量上下文。上下文会影响逗号运算符的工作方式,从而产生不同的结果:
"二进制 "," 是逗号运算符。在标量上下文中,它计算左参数,丢弃该值,然后计算右参数并返回该值。"
@987654321 @
因此:b
要理解以:@a[0] 开头的行,请考虑:
($a, $b, $c) = ("a", "b", "c", "d"); # here the "d" is discarded
print $a, $b, $c; # this prints: abc
($a, $b) = ("a", "b", "c"); # here the "c" is discarded
($a) = ("a", "b"); # here the "b" is discarded
($a[0]) = ("a", "b"); # here the "b" is discarded
看起来,行首的括号创建了一个列表上下文。这几乎就是它所说的:http://docstore.mik.ua/orelly/perl4/prog/ch02_07.htm
"分配给一个标量列表也会在右侧提供一个列表上下文,即使列表中只有一个元素"
@ 在行首也会创建一个列表上下文:
@a[0] = ("a", "b") 表示以与上述相同的方式评估 RHS,即丢弃“b”