tags:

views:

147

answers:

4

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 dir. the output dir should be given as a parameter

+3  A: 

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.

Sinan Ünür
Thanks, I'm Aware of this option, but i want to know if there is some hack to pass parameter (not using global).
jojo
A: 

UPDATE: I like File::Find::Wanted better than File::Find. However, brian's module is probably closer to what you really want.

molecules
+4  A: 

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.

brian d foy
This may work for me
jojo
+4  A: 

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