6

Possible Duplicate:
How do I pass parameters to the File::Find subroutine that processes each file?

One can use Perl's File::Find module like this:

find( \&wanted, @directories);

How can we add a parameter to the wanted function?

For example, I want to traverse the files in /tmp extracting some information from each file and the result should be stored to a different directory. The output dir should be given as a parameter.

Community
  • 1
  • 1
jojo
  • 3,614
  • 1
  • 25
  • 21
  • Please describe more specifically what you are trying to do and I will update my answer. – Sinan Ünür Feb 02 '10 at 10:59
  • See also http://stackoverflow.com/questions/2056649/how-do-i-pass-parameters-to-the-filefind-subroutine-that-processes-each-file – Sinan Ünür Feb 02 '10 at 11:49
  • @ Sinan Ünür your remark http://stackoverflow.com/questions/2056649/how-do-i-pass-parameters-to-the-filefind-subroutine-that-processes-each-file solved the my question. if you post it as an answer i will marked as accepted – jojo Feb 02 '10 at 12:09
  • @ilang7 In that case, I vote to close your question as "exact duplicate". – Sinan Ünür Feb 02 '10 at 12:17
  • @Sinan Ünür you are right, it is duplicate , shame on me – jojo Feb 02 '10 at 12:21
  • 1
    @ilang7 No need for any shame on anyone. – Sinan Ünür Feb 02 '10 at 12:24
  • UPDATE: I like [File::Find::Wanted](http://search.cpan.org/dist/File-Find-Wanted/Wanted.pm) better than File::Find. However, brian's module is probably closer to what you really want. – Christopher Bottoms Feb 02 '10 at 11:59

3 Answers3

10

You use a closure:

use File::Copy;

my $outdir= "/home/me/saved_from_tmp";
find( sub { copy_to( $outdir, $_); }, '/tmp');

sub copy_to
  { my( $destination_dir, $file)= @_;
    copy $file, "$destination_dir/$file" 
      or die "could not copy '$file' to '$destination_dir/$file': $!";
  }
mirod
  • 15,923
  • 3
  • 45
  • 65
4

You can create any sort of code reference you like. You don't have to use a reference to a named subroutine. For many examples of how to do this, see my File::Find::Closures module. I created that module to answer precisely this question.

Borodin
  • 126,100
  • 9
  • 70
  • 144
brian d foy
  • 129,424
  • 31
  • 207
  • 592
3

File::Find's contract specifies what information is passed to &wanted.

The wanted function takes no arguments but rather does its work through a collection of variables.

  • $File::Find::dir is the current directory name,
  • $_ is the current filename within that directory
  • $File::Find::name is the complete pathname to the file.

If there is extra information you want to make available in the callback, you can create a sub reference that calls your wanted sub with the desired parameters.

Community
  • 1
  • 1
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • Thanks, I'm Aware of this option, but i want to know if there is some hack to pass parameter (not using global). – jojo Feb 02 '10 at 11:49