假设我有这个清单:
my @list = qw(one two three four five);
Run Code Online (Sandbox Code Playgroud)
我想抓住所有包含的元素o.我有这个:
my @containing_o = grep { /o/ } @list;
Run Code Online (Sandbox Code Playgroud)
但是我还需要做些什么才能获得索引,或者能够访问索引中的索引grep?
mob*_*mob 16
my @index_containing_o = grep { $list[$_] =~ /o/ } 0..$#list; # ==> (0,1,3)
my %hash_of_containing_o = map { $list[$_]=~/o/?($list[$_]=>$_):() } 0..$#list
# ==> ( 'one' => 0, 'two' => 1, 'four' => 3 )
Run Code Online (Sandbox Code Playgroud)
Eth*_*her 12
看看List :: MoreUtils.你可以使用数组做很多方便的事情,而不必滚动你自己的版本,而且它更快(因为它在C/XS中实现):
use List::MoreUtils qw(first_index indexes);
my $index_of_matching_element = first_index { /o/ } @list;
Run Code Online (Sandbox Code Playgroud)
对于所有匹配的索引,然后是它们的相应元素,您可以:
my @matching_indices = indexes { /o/ } @list;
my @matching_values = @list[@matching_indices];
Run Code Online (Sandbox Code Playgroud)
要不就:
my @matching_values = grep { /o/ } @list;
Run Code Online (Sandbox Code Playgroud)