Question

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;
Was it helpful?

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

OTHER TIPS

I think you're using it in the right way. The only things you can do is to wrap the find function inside another one that creates the array (with push) and then return it.

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

In this way you can have what you were looking for, but it's almost the same as you have done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top