OK, so every time someone here asks how to walk a directory tree and process files we all religiously (!) chant the File::Find mantra.
The truth is that I have always hated File::Find. It just feels old.
My main gripe is that the wanted function, which is called for each file found, does not accept arguments. So if I really need arguments, which happens quite often, then I have to use good ole globals. This is definitely _not_ what I'd call good coding practice. Plus how do I put this code in a module?
So here is my solution, using closures to generate various functions from a single "template" one. The interesting part is really the make_wanted function, that takes a code reference and a list of arguments, and generates a function (with takes no arguments) that will call the code reference with the arguments (which will have the value they had when make_wanted was called):
#!/bin/perl -w
use strict;
use File::Find;
# create various wnated functions
my $wanted= make_wanted( \&wanted_1, 'toto', 'tata');
find( $wanted, '.');
print "\n";
$wanted= make_wanted( \&wanted_1, 'foo', 'bar', 'baz');
find( $wanted, '.');
print "\n";
$wanted= make_wanted( \&wanted_2, 'toto', 'tata');
find( $wanted, '.');
print "\n";
$wanted= make_wanted( \&wanted_2, 'foo', 'bar', 'baz');
find( $wanted, '.');
print "\n";
# a regular function, can access its arguments and the File::Find vari
+ables
sub wanted_1
{ my @args= @_;
print "wanted_1( ", join( ', ', @args), ") on $_\n" if( m/\.xml$/)
+;
}
sub wanted_2
{ my @args= @_;
print "wanted_2( ", join( ', ', @args), ") on $_\n" if( m/\.txt$/)
+;
}
# the closure generator
# creates a function that calls the function passed as first argument
# passing it the arguments make_wanted is called with
sub make_wanted
{ my $wanted= shift; # get the "real" wanted fu
+nction
my @args= @_; # "freeze" the arguments
my $sub= sub { $wanted->( @args); }; # generate the anon sub
return $sub; # return it
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.