perl - perl 中 $name 和 ($name) 变量的区别

标签 perl

这个问题在这里已经有了答案:





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/

相关文章:

linux - TAP::Harness perl 测试 tee 输出

regex - 使用 Perl 正则表达式匹配字符串的一部分

linux - Perl - 如何将输入拆分为数组?

mysql - 在 sql 结果中填充空日期的最直接方法是什么(在 mysql 或 perl 端)?

Perl 6 - 接受 "Bareword"输入的子程序

perl - Unicode 就绪字搜索 - 问题

perl 一行只保留所需的行

perl - 在远程机器上查找/tmp 中的可用空间

JAVA 到 Perl - 端口 XOR 加密器类

perl - 为什么 perl 打印文件句柄语法是这样的?