Search code examples
arraysstringperlindices

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


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?


Solution

  • 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