这个问题在这里已经有了答案:
What's the difference between my ($variableName) and my $variableName in Perl?
(4 个回答)
6年前关闭。
我想知道是否有人可以解释 $name
之间的区别和 ($name)
.
例如:
my @objects = ('specs','books','apple');
my ($fruit) = grep { $_ eq 'apple'} @objects;
这给出了
$fruit = 'apple'
的结果.但是,如果将第二条语句修改为:$fruit = grep { $_ eq 'apple'} @objects;
水果的值被评估为
1
.这是否与 grep
相关/特定? ?
最佳答案
my $fruit =
分配到标量上下文中。my ($fruit) =
分配到列表上下文中(就像 my @fruit =
一样)。
grep documentation说:
returns the list value consisting of those elements for which the expression evaluated to true. In scalar context, returns the number of times the expression was true.
它正在有效地使用 wantarray在内部确定它应该给出什么类型的返回值。您可以在自己的子程序中使用它来获得类似的效果,但是 you might not want to .
关于perl - perl 中 $name 和 ($name) 变量的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33413940/