Hello TomJerry, and welcome to the Monastery!

Consider the following quote from I/O Operators:

A (file)glob evaluates its (embedded) argument only when it is starting a new list. All values must be read before it will start over. In list context, this isn’t important because you automatically get them all anyway. However, in scalar context the operator returns the next value each time it’s called, or undef when the list has run out.

Although this doesn’t explain why the while version of sub traverse_file produces an infinite loop, it is suggestive: All values must be read before it will start over. It looks as though the while version — which evaluates the glob function in scalar context, but makes a recursive call before the original list of filenames has been exhausted — is exhibiting what in C would be called “undefined behaviour.”

I think the documentation could be clearer on this point, but the moral is apparent: use glob in scalar context only if the list it returns will be exhausted before the next call to glob. In all other cases, use glob in list context, as in the foreach version of sub traverse_file. This is always the safer option.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: foreach vs. while inside a directory traversing subroutine by Athanasius
in thread foreach vs. while inside a directory tranversing subroutine by locked_user TomJerry

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.