Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

comment on

( [id://3333] : superdoc . print w/replies, xml ) Need Help??

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


In reply to Re: file globbing in a nested while loop by trantor
in thread file globbing in a nested while loop by George_Sherston

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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.