以下代码段搜索数组中第一次出现值的索引.但是,当删除$ index周围的括号时,它无法正常运行.我究竟做错了什么?
my ($index) = grep { $array[$_] eq $search_for } 0..$#array;
Run Code Online (Sandbox Code Playgroud)
Mic*_*man 43
括号grep将从标量上下文到列表上下文的上下文更改.在标量上下文中grep返回表达式为真的次数.在列表上下文中,它返回表达式为true的元素.
以下重点介绍了差异背景:
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/
Run Code Online (Sandbox Code Playgroud)
我认为你正在寻找first_index从列表:: MoreUtils:
use List::MoreUtils qw( first_index );
# ...
my $index = first_index { $_ eq $search_for } @array;
Run Code Online (Sandbox Code Playgroud)
grep函数在列表上下文和标量上下文中的行为不同.记录在perldoc -f grep:
计算LIST的每个元素的BLOCK或EXPR(在每个元素的本地设置$ _)并返回由表达式求值为true的元素组成的列表值.在标量上下文中,返回表达式为true的次数.
您可以使用命名不佳的wantarray函数自行复制:
sub my_grep {
my $sub = shift;
my @return;
for my $item (@_) {
push @return if $sub->($item);
}
return @return if wantarray;
return scalar @return;
}
Run Code Online (Sandbox Code Playgroud)