in reply to More Fileglob in scalar context question

Here's a helpful explanation from perlop of this odd behavior of the glob operator:
A glob evaluates its (embedded) argument only when it is starting a new list. All values must be read before it will start over. In a list context this isn't important, because you automatically get them all anyway. In scalar context, however, the operator returns the next value each time it is called, or a undef value if you've just run out. As for filehandles an automatic defined is generated when the glob occurs in the test part of a while or for - because legal glob returns (e.g. a file called 0) would otherwise terminate the loop. Again, undef is returned only once. So if you're expecting a single value from a glob, it is much better to say ($file) = <blurch*>; than $file = <blurch*>; because the latter will alternate between returning a filename and returning FALSE.
So, even though you've changed the argument to this glob() in your loop, the glob doesn't notice that the argument has changed until it finishes with the argument it got the first time it was called. And it takes two iterations for the glob to finish that argument: once to get the matching file and once to realize that there are no more files.

If you use the doc's suggested solution your problem should disappear!

Replies are listed 'Best First'.
Re: Re: More Fileglob in scalar context question
by scain (Curate) on Jul 02, 2001 at 19:52 UTC
    Chipmonk,

    Thank you. I can't figure out how I missed that in perlop, as I did spend some time trying to figure this out before posting.

    As for how to do this better (i.e., so it works), I posted a follow up to my node on Friday that indicated that I was more comfortable doing this in a list context anyway. That is, get all of the matching files before going into the loop and then using foreach to go through each of them.

    Thanks again,
    Scott