Perl有没有内置函数来获取数组中元素的索引?或者我需要自己写一个这样的函数?相当于PHP array_search()或JavaScript array.indexOf()
发布于 2010-07-11 14:52:16
use List::Util qw(first);
$idx = first { $array[$_] eq 'whatever' } 0..$#array;
(List::Util是核心)
或
use List::MoreUtils qw(firstidx);
$idx = firstidx { $_ eq 'whatever' } @array;
(List::MoreUtils在CPAN上)
发布于 2010-07-11 18:15:46
下面是5.10之后的一种方法,增加了确定有多少索引与给定值匹配的好处。
my @matches = grep { $array[$_] ~~ $element } 0 .. $#array;
如果保证所有元素都是唯一的,或者只有第一个索引是感兴趣的:
my ($index) = grep { $array[$_] ~~ $element } 0 .. $#array;
发布于 2010-07-11 20:55:23
这是一个autobox
解决方案:
use autobox::Core;
my @things = qw/blue black green red green yellow/;
my $first_green = @things->first_index( sub{ $_[0] eq 'green' } ); # code block
my $last_green = @things->last_index ( qr/^green$/ ); # or regex
say $first_green; # => 2
say $last_green; # => 4
https://stackoverflow.com/questions/3222138
复制相似问题