Perl - searching for partial matches in string array and returning matching indices

StackOverflow https://stackoverflow.com/questions/16492428

  •  21-04-2022
  •  | 
  •  

سؤال

Suppose I have a string array @file_paths which contains

@file_paths= ["C:\Lazy\FolderA\test.cpp", "C:\Lazy\FolderA\test2.cpp", 
              "C:\Lazy\FolderB\test.cpp", "C:\Lazy\FolderB\test2.cpp", ... etc]

I want to be able to find the array indices corresponding to the FolderA positions, FolderB, positions.. and so on.

i.e something like @file_paths.indices("FolderA") would return @indices = [0,1] and @file_paths.indices("FolderB") would return @indices = [2,3].. etc

The trick is I'd be doing a contains function on @file_paths to get the corresponding indices. What would the subroutine look like?

هل كانت مفيدة؟

المحلول

Here is the answer: http://bit.ly/13LE8K0

you can use 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";

says

2 3

نصائح أخرى

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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top