zebullon zebullon - 7 months ago 10
Perl Question

Using file find to grab source files

I am trying to use (as an exercise) the file find callback capability to filter source files out. It does not work so far and just grab everything under the sun.

could you point me out in the good direction ?

#!/usr/local/bin/perl
use strict;
use warnings;

use File::Find;

my @srcFiles;
my @srcExt = qw(cpp h py pl);


my @startDir = qw(.);
find( sub{
my @fields = split /'.'/, $File::Find::name;
push @srcFiles, $File::Find::name if grep $fields[-1], @srcExt;
},
@startDir);
print 'Source files found: ', @srcFiles;


Thanks

Answer

Your problem is in your split

 my @ar =  split /'.'/, $File::Find::name;
                   ^
            here is your problem.

you want to split the file using dot so, you tried '.'. But it is not escaping. Escape the character use back slash. So must be

my @ar =  split /\./, $File::Find::name;

So your code is

find( sub{
     my @fields = split /\./, $File::Find::name;
     push @srcFiles, $File::Find::name if grep $fields[-1], @srcExt;
 }, 
 @startDir);  

Or else something try this,

Join the array by the pipe separated. Then use precompiled regex(qr) to add the non capturing group. Then parse variable into the subroutine and check it.

#!/usr/local/bin/perl
use strict;
use warnings;

use File::Find;

my @srcFiles;
my @srcExt = qw(cpp h py pl);
my $match = join("|",@srcExt);
$match = qr/\.(?:$match)$/;

my @startDir = qw(.);

find(sub
{
    my $s = $File::Find::name;
    push(@srcFiles,$s) if($s =~m/$match/);

}
, @startDir);

print @srcFiles;