perl获取数组中匹配项的索引

Rad*_*adz 3 perl

我想在数组中搜索一个元素.我想从这个搜索得到的是我找到匹配的数组的所有索引.

所以,例如我要搜索的单词是:

$myWord = cat

@allMyWords = my whole file with multiple occurrences of cat in random positions in file
Run Code Online (Sandbox Code Playgroud)

因此,如果cat出现在第3,19和110位,我希望这些指数成为它的结果.我想知道是否有一个小而简单的方法来做到这一点.

谢谢!

Rad*_*adz 8

我得到了答案.这是将返回数组中我们要搜索的元素的所有索引的代码.

my( @index )= grep { $allMyWords[$_] eq $word } 0..$#allMyWords;
print "Index : @index\n";   
Run Code Online (Sandbox Code Playgroud)


Eth*_*her 7

使用List :: MoreUtils:

use List::MoreUtils qw(indexes);

my @indexes = indexes { $_ eq 'cat' } @words;
Run Code Online (Sandbox Code Playgroud)

如果您尚未阅读该文件,可以使用"slurp mode"读取它:

local $/; # enable slurp mode
my @words = split(/\s+/, <>);
Run Code Online (Sandbox Code Playgroud)