Reputation: 117
The pattern I want to match is *_name.txt
The directory I want to search is $dir ($dir has many subdirectories, which is why I need File::Find
rather than glob
I am not going to use Find::Find::Rule
( I know it has easy code for this, but when I ran, it had non-existing file errors. I do not want to add additional files to my perl library)
The syntax I have so far is
use File::Find;
find(\&store_foundfiles,$dir);
sub store_foundfiles {
my @string = *_name.txt;
#I DONT KNOW FROM HERE ON"
#I WANT TO IMPLEMENT THE FOLLOWING...
#FOREACH MATCH ON @string, STORE THE MATCH TO ARRAY '@found'
}
Upvotes: 1
Views: 3554
Reputation: 239861
Adding this because most people should probably use File::Find::Rule for this, even if you have a reason not to:
use File::Find::Rule;
my @files = File::Find::Rule->file->name("*_name.txt")->in($dir);
Upvotes: 5
Reputation: 1364
use strict;
use warnings;
use File::Find;
my @found;
find(
sub {
push @found, $File::Find::name if /_name[.]txt\z/;
# or push @found, $File::Find::name if substr($_, -9) eq '_name.txt';
},
$dir,
);
for my $file (@found) { ... }
The array is declared outside of the subroutine so it sticks around outside of the subroutine's scope. If you have a very large number of files, you may want to process each one as it's encountered rather than storing them all in an array and looping through that (NB: some operations cannot be done lazily, like sorting).
$File::Find::name
is pushed rather than $_
because the absolute path is likely more useful. Push $_
instead if you just want the base filename.
Upvotes: 3