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

Hi Monks,

I am calling file::find to find a list of files that match my criteria. No problem there. But, I want to see if I can do it without using a global to keep an array of the files found...

I don't see a way to pass in any parameters, and therefore don't see a way around it...true?

--------------------------------
moderator suggestion: When I search for "file::find" it only gives perldoc, I would like to see all user posts

Replies are listed 'Best First'.
Re: file::find question
by jdporter (Paladin) on Nov 21, 2002 at 03:39 UTC
    I want to see if I can do it without using a global
    You can use a lexical variable in an enclosing scope. E.g.
    sub do_things_with_files { my @files_found; find( sub { if ( ... ) { push @files_found, $File::Find::name; } }, '.' ); }
    Even if the variable is at file scope level, it's still lexical, not global, if it's declared with "my".

    For further info, you might want to check out the recent tutorial, "Lexical scoping like a fox".

    When I search for "file::find" it only gives perldoc, I would like to see all user posts
    Use the Super Search.

    jdporter
    ...porque es dificil estar guapo y blanco.

      Thanks for the help!!

      I need to remember the global vs filescope stuff, as I am really not using a global, but a file scope lexical (my).

      I need to pass a function to find because it is pretty long...so I *really* don't want to use "sub {}"

      With that in mind, there is no way around this?

      BTW, when I use Tk, it allows you to pass
      [\&sub, $var1, var2]
      ANYWHERE it takes a function reference, but I am assuming that it is Tk specific...

      Guess I'll stick with the 'my' variable if need be ;-)

        You can write:

        { # enclosing scope my @found_files; sub criteria { # do the right thing } } find(\&criteria,$dir);

        Of course, now you have to decide how large a part of your script needs access to the @found_files variable.

        -- 
                dakkar - Mobilis in mobile
        
        You know, I could probably help you better if you'd say what it is you're trying to do. If you're just using File::Find to find a list of filenames, and then doing something with those names later, you could write a little wrapper around find like this:
        sub find_files(&@) { my( $criteria_cr, @dirs ) = @_; my @found; find( sub { $criteria_cr->( $File::Find::name ) and push @found, $File::Find::name; }, @dirs ); @found } # then you could call it like this: my @html_files = find_files { /\.html$/ } '.'; my @abc_subdirs = find_files { -d $_[0] } 'a', 'b', 'c';
        Don't be afraid to use 'my' variables for purposes such as this. It is the very natural, perlish thing to do.

        jdporter
        ...porque es dificil estar guapo y blanco.