zebullon
zebullon

Reputation: 203

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

Upvotes: 0

Views: 95

Answers (2)

mkHun
mkHun

Reputation: 5921

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 syntax should 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 try something as follow, this is more effective than your code and it will fix some bugs as @hobbs mentioned in a comment.

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;

Upvotes: 4

user149341
user149341

Reputation:

my @fields = split /'.'/, $File::Find::name;

This regular expression splits the filename where it finds an apostrophe, followed by any character, followed by an apostrophe. This is definitely not what you intended.

Instead, try:

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

Upvotes: 1

Related Questions