Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: file globbing in a nested while loop

by trantor (Chaplain)
on Oct 05, 2001 at 17:10 UTC ( [id://116983]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://116983]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (2)
As of 2024-04-25 23:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found