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

How do I get &wanted to return a list of a files matching the criteria in &wanted. I can't access a my variable of the calling rountine from within &wanted.
  • Comment on How to get File::Find to return a list?

Replies are listed 'Best First'.
•Re: How to get File::Find to return a list?
by merlyn (Sage) on Jan 06, 2005 at 22:36 UTC
Re: How to get File::Find to return a list?
by Zaxo (Archbishop) on Jan 06, 2005 at 22:31 UTC

    You'll need a (package) global array to push results onto. That is one thing that many dislike about File::Find. You can localize it and pass it out to a lexical if you like,

    my @found_array = do { local @found; find \&wanted, $dir; @found }; sub wanted { no strict 'vars'; push @found, $_ # if . . . }

    After Compline,
    Zaxo

Re: How to get File::Find to return a list?
by osunderdog (Deacon) on Jan 06, 2005 at 23:37 UTC

    It doesn't have to be a global. I like the closure solution:

    use strict; use File::Find; print "starting a find \n"; print join("\n", myfind('.')) . "\n"; sub myfind { my $dir = shift; my $list = []; find({wanted=>sub{findcb($list)}}, $dir); return((wantarray)?(@$list):($list)); } sub findcb { my $listref = shift; push @$listref, $File::Find::name; }

    This is a closure right?


    "Look, Shiny Things!" is not a better business strategy than compatibility and reuse.

Re: How to get File::Find to return a list?
by borisz (Canon) on Jan 06, 2005 at 22:38 UTC
    use File::Find; my @files; find( { wanted => sub { push @files, $File::Find::name if -M; } }, '/dir' );
    Boris
Re: How to get File::Find to return a list?
by Anonymous Monk on Jan 06, 2005 at 22:26 UTC
    Me again. Basically I want to use find like grep: my @files = find { -M > 20 } @DIRS;