Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Okay, when I first looked up File::Find, I naively expected that I might be able to write a line something along the lines of:

my @files = find(\&some_selection_function, $dir);

--hmmm. Seems that approach won't work because find ignores the return value of the function it calls. The only way (that I know of) to push values onto @files is to have a line like this in some_selection_function:

push @files, $_;

The only problem with that is, @files needs to be a global variable for this to work (I think), and it's not terribly clear from the line that calls find that I'm altering @files.

Anybody know of a way around this? I.e., a simple way to collect all the files that find finds?

Replies are listed 'Best First'.
Re: File::Find without global variables?
by diotalevi (Canon) on Aug 24, 2005 at 23:31 UTC

    It doesn't have to be a global. A closure can handle this just fine too.

    my @files; find ( sub { some_selection_function( \ @files ) }, $dir ); sub some_selection_function { my ( $files ) = @_; ... push @$files, $File::Find::name; }
Re: File::Find without global variables?
by itub (Priest) on Aug 24, 2005 at 23:31 UTC
    File::Find is known for having an "odd" interface, to say the least. You can try File::Find::Rule for an alternative interface that is generally more convenient and clearer.
Re: File::Find without global variables?
by osunderdog (Deacon) on Aug 25, 2005 at 01:41 UTC
Re: File::Find without global variables?
by Anonymous Monk on Aug 25, 2005 at 02:58 UTC
    Thanks for the help, all. I thought this would be a question that would have been answered already, as osunderdog pointed out, but his link didn't show up using a simple search using the term "file::find." And I think I'll be using one of the modules Randal or itub mentioned at home, but at work (where I don't have the leeway to install modules), I'll try diotalevi's approach. Thanks again!