Search code examples
perlfile-find

Is there a cleaner way for File::Find to return a list of wanted files?


I find the design choice behind File::Find::find a little surprising. The examples I've come across all show find used in void context.

The documentation also clarifies that the \&wanted coderef in find( \&wanted, @dirs ) is not meant to be a filter (emphasis my own):

The wanted() function does whatever verifications you want on each file and directory. Note that despite its name, the wanted() function is a generic callback function, and does not tell File::Find if a file is "wanted" or not. In fact, its return value is ignored.


But what if I do want to use it as a filter in a manner similar to grep? I'm curious to know if there's another way to write the following:

use strict;
use warnings;
use feature 'say';

use File::Find;

my $wanted = qr/^\d{2}_/;  # e.g.

my @wanted;
find( sub { -f && /$wanted/ && push @wanted, $_ }, '.' );

# I wish my @wanted = find( ... ); worked

say for @wanted;

Solution

  • Looking on CPAN, I find several alternative interfaces to File::Find available that aim to simplify the interface.

    I would try File::Finder, by well-known Perl expert Randal Schwartz, first.

    File::Find::Rule is another one.

    (It is probably safe to say that, if people are writing modules to do this, there is no easy built-in way to do it.)