-3

假设我有一个字符串数组@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 上执行 contains 函数来获取相应的索引。子程序会是什么样子?

4

2 回答 2

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
于 2013-05-11T00:47:09.867 回答
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;
}
于 2013-05-11T00:14:48.377 回答