Perl - 在字符串数组中搜索部分匹配并返回匹配的索引

时间:2013-05-11 00:05:02

标签: arrays string perl indices

假设我有一个包含

的字符串数组@file_paths
@file_paths= ["C:\Lazy\FolderA\test.cpp", "C:\Lazy\FolderA\test2.cpp", 
              "C:\Lazy\FolderB\test.cpp", "C:\Lazy\FolderB\test2.cpp", ... etc]

我希望能够找到与FolderA位置,FolderB,位置等对应的数组索引。

@file_paths.indices("FolderA")之类的内容会返回@indices = [0,1]               并且@file_paths.indices("FolderB")会返回@indices = [2,3] ..等等

诀窍是我要在@file_paths上做一个包含函数来获取相应的索引。子程序会是什么样的?

2 个答案:

答案 0 :(得分:2)

以下是答案:http://bit.ly/13LE8K0

您可以使用CPAN List::MoreUtils

use 5.012;
use strict;
use warnings;
use List::MoreUtils qw(indexes);

my @file_paths= qw(
        C:\Lazy\FolderA\test.cpp C:\Lazy\FolderA\test2.cpp
        C:\Lazy\FolderB\test.cpp C:\Lazy\FolderB\test2.cpp
);

my @ind = indexes {$_ =~ /FolderB/} @file_paths;
say "@ind";

2 3

答案 1 :(得分:0)

my @file_paths= ("C:\\Lazy\\FolderA\\test.cpp", "C:\\Lazy\\FolderA\\test2.cpp", 
              "C:\\Lazy\\FolderB\\test.cpp", "C:\\Lazy\\FolderB\\test2.cpp");

my @aIndices = indices("FolderA", @file_paths);


sub indices {
  my ($keyword, @paths) = @_;
  my @results = ();

  for ( my $i = 0; $i < @paths; ++$i )
  {
    if ($paths[$i] =~ /\\$keyword\\/)
    {
      push @results, $i;
    }
  }

  return @results;
}