以下代码片段搜索数组中第一次出现值的索引。但是,当删除$ index周围的括号时,它无法正常工作。我究竟做错了什么?
my ($index) = grep { $array[$_] eq $search_for } 0..$#array;
解决方法
括号将grep从标量上下文的上下文更改为列表上下文。在标量上下文中,grep返回表达式为真的次数。在列表上下文中,它返回表达式为真的元素。
以下突出显示差异上下文:
my $x = grep {/foo/} @array; # the number of things that match /foo/ my ($x) = grep {/foo/} @array; # the first thing that matches /foo/ my @foo = grep {/foo/} @array; # all the things that match /foo/ my (@foo) = grep {/foo/} @array; # all the things that match /foo/