【问题标题】:perl Get indexes of matches in arrayperl 获取数组中匹配项的索引
【发布时间】:2015-11-18 20:16:11
【问题描述】:

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

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

$myWord = cat

@allMyWords = my whole file with multiple occurrences of cat in random positions in file

所以,如果 cat 出现在第 3、第 19 和第 110 位,我想要这些索引作为它的结果。我想知道是否有一种小而简单的方法可以做到这一点。

谢谢!

【问题讨论】:

    标签: perl


    【解决方案1】:

    我得到了答案。这段代码将返回数组中我们正在搜索的元素的所有索引。

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

    【讨论】:

    • 但这是一个小问题。总的来说,这看起来是最优雅的方法。
    • 对于像我这样正在寻找与此等效的字符串的人:my @locations = grep { substr($aString, $_, 1) eq "C" } 0..(length($aString));
    【解决方案2】:

    List::MoreUtils:

    use List::MoreUtils qw(indexes);
    
    my @indexes = indexes { $_ eq 'cat' } @words;
    

    如果你还没有读过文件,你可以使用“slurp模式”来读:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多