为什么我的Perl grep不能返回第一场比赛?

前端之家收集整理的这篇文章主要介绍了为什么我的Perl grep不能返回第一场比赛?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下代码片段搜索数组中第一次出现值的索引。但是,当删除$ 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/
原文链接:https://www.f2er.com/Perl/173032.html

猜你在找的Perl相关文章