Search code examples
perlfindfile-exists

How to verify more than 1 file exist with a given file extension in perl


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 :)


Solution

  • 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;
        }
    }