in reply to foreach vs. while inside a directory tranversing subroutine
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, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: foreach vs. while inside a directory tranversing subroutine
by locked_user TomJerry (Initiate) on May 26, 2015 at 06:25 UTC |