Filehandles and dirhandles are global, so each time this sub is called, DIR is closed and re-opened on a new directory. To avoid that, pass a scalar to opendir() instead of a literal name. When a scalar is passed as the first parameter to open() or opendir(), it is used as the name of the filehandle/dirhandle to open. Likewise with readdir(), <>, read() and other functions that take filehandle/dirhandle parameters.

my $dh = $startDir;
$dh =~ s/\W/_/g; # Transform all non-alphanumerics to _

opendir $dh, $startDir || die $!;

while (my $entry = readdir($dh)) {

Actually, it is easier than this, see:


<http://www.perldoc.com/perl5.8.0/pod/perlfaq5.html#How-can-I-make-a-filehandle-local-to-a-subroutine---How-do-I-pass-filehandles-between-subroutines---How-do-I-make-an-array-of-filehandles->

"As of perl5.6, open() autovivifies file and directory handles as references if you pass it an uninitialized scalar variable ".

Which means, all you do is this:

my $dh;
opendir $dh, $startDir || die $!;
while (my $entry = readdir($dh)) {

So just us a "my" local scalar variable set to undef before the opendir call.

Enjoy,
   Peter.

--
<http://www.interarchy.com/>  <http://documentation.interarchy.com/>

Reply via email to