http://qs321.pair.com?node_id=116983


in reply to file globbing in a nested while loop

I absolutely agree with the other posters and I think that File::Find is the solution.

However if you want to fix your program keep a couple of things in mind: check if you're following symlinks and get the list at once evaluating <glob> in a list context instead of scalar context, for it might be confusing when mixed with recursion. You always use <*/> and if perl uses some sort of caching, in a scalar context, even in a deeper level of recursion, you'd get a file from the previous list of globbed files!

And symbolic links can lead you to infinite recursion as well.

To clarify with an example, I found out that this script is easily fooled by symlinks and even if there aren't any it goes into infinite recursion:

#!/usr/bin/perl -w use strict; sub do_list { my($level, $base_path) = @_; my @list; # @list = <$base_path/*>; # for (@list) { while(<$base_path/*>) { print '>' x $level, ' '; print "$_\n"; next if -l $_; if(-d "$_") { do_list($level + 1, $_) } } $level--; } do_list(1, $ARGV[0] || '.');

Now, just get rid of the while and use the assignment and the for loop instead: evaluating the glob in list context prevents interferences between recursion and the "next" value returned by the "right" glob expression.

-- TMTOWTDI