Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a parameter to the wanted function when using Perl's File::Find? [duplicate]

Tags:

perl

file-find

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.

like image 607
jojo Avatar asked Feb 02 '10 10:02

jojo


2 Answers

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': $!";
  }
like image 132
mirod Avatar answered Sep 30 '22 19:09

mirod


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.

like image 22
brian d foy Avatar answered Sep 30 '22 19:09

brian d foy