I have a directory /var/spool
and inside that, directories named
a b c d e f g h i j k l m n o p q r s t u v x y z
An
People keep recommending File::Find, but the other piece that makes it easy is my File::Find::Closures, which provides the convenience functions for you:
use File::Find;
use File::Find::Closures qw( find_by_regex );
my( $wanted, $reporter ) = find_by_regex( qr/^\d+\.\z/ );
find( $wanted, @directories_to_search );
my @files = $reporter->();
You don't even need to use File::Find::Closures
. I wrote the module so that you could lift out the subroutine you wanted and paste it into your own code, perhaps tweaking it to get what you needed.
Use File::Find to traverse a directory tree.
As others have noted, use File::Find:
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
find(\&find_emails => '/var/spool');
sub find_emails {
return unless /\A[0-9]+[.]\z/;
return unless -f $File::Find::name;
process_an_email($File::Find::name);
return;
}
sub process_an_email {
my ($file) = @_;
print "Processing '$file'\n";
}
You can use File::Find.
Try this:
sub browse($);
sub browse($)
{
my $path = $_[0];
#append a / if missing
if($path !~ /\/$/)
{
$path .= '/';
}
#loop through the files contained in the directory
for my $eachFile (glob($path.'*'))
{
#if the file is a directory
if(-d $eachFile)
{
#browse directory recursively
browse($eachFile);
}
else
{
# your file processing here
}
}
}#browse
For a fixed level of directories, sometimes it's easier to use glob than File::Find:
while (my $file = </var/spool/[a-z]/user/*/*>) {
print "Processing $file\n";
}