Reputation: 159
I have a directory "logs" which contains sub-directories as "A1", "A2", "A3", "B1", "B2", "B3".
I want to write a perl code that search all the sub directories with name pattern as "A", i.e. all the directories names starting from character A.
Please help me.
Upvotes: 1
Views: 478
Reputation: 126722
File::Find
is overkill for simply searching a directory. opendir
/readdir
still has a purpose!
This program does a chdir
to the specified directory so that there is no need to build the full path from the names generated by readdir
.
The directory to search and the required prefix can be passed as command-line parameters and will default to logs
and A
if they are not supplied.
use strict;
use warnings;
use autodie;
my ($dir, $prefix) = @ARGV ? @ARGV : qw/ logs A /;
chdir $dir;
my @wanted = do {
opendir(my $dh, '.');
grep { -d and /^\Q$prefix/ } readdir $dh;
};
print "$_\n" for @wanted;
Upvotes: 0
Reputation: 13792
Use the Perl core module File::Find:
use strict;
use warnings;
use File::Find;
#Find in 'logs' directory, assume the script is executed at this folder level
find(\&wanted, 'logs');
sub wanted {
#Subroutine called for every file / folder founded ($_ has the name of the current)
if(-d and /^A/ ) {
print $_, "\n";
}
}
Update: If you want to parametrize the prefix, you can do this:
use strict;
use warnings;
use File::Find;
my $prefix = 'B';
find(\&wanted, 'logs');
sub wanted {
if(-d and /^$prefix/ ) {
print $_, "\n";
}
}
Upvotes: 2