Reputation: 7164
My requirement is to know whether are at least 2 .wav
files in a directory.
Currently I'm using grep(/\.wav$/,readdir($dir))
to get the number of .wav
files exist and then check whether its greater than 1
.
But I really don't want to count all the files if there were 1000s
of them.
Anyone have better solution for this...
Thank you :)
Upvotes: 0
Views: 216
Reputation: 50677
In scalar context you can iterate over directory items using while()
, and immediately break the loop when your condition is met,
my $count = 0;
while (defined(my $f = readdir $dir)) {
if ($f =~ /\.wav$/ and ++$count >= 2) {
print "there are at least two wav files\n";
last;
}
}
Upvotes: 4
Reputation: 4974
You can use glob
to expand the list of files in a directory with widcards, or better bsd_glob
from package File::Glob
:
use File::Glob ':bsd_glob';
my @wavfiles = bsd_glob("$your_directory/*.wav");
my $count_wavs = @wavfiles;
Note that the count of files is using an array in scalar context.
bsd_glob
is better because it handles correctly spaces in directory names (amongst others), prefer this one on glob
.
Upvotes: 0