in reply to glob weirdness / list contexts?
From perlop.pod (which is pointed to from "perldoc -f glob"):
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 C run out[sic]. As with filehandle reads, an automatic defined is generated when the glob occurs in the test part of a while, 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 you have one case of using an array in a scalar context which returns the number of elements in the array which would be true if-and-only-if at least one file matched the glob. The other case is using glob in a scalar context which will return the "next matching file" from the first time glob was called (from that spot in your code) and then will return undef, ignoring the argument you pass in everytime except the first time and right after each time it returns undef.
For a long time I've felt that "using glob in a scalar context" should have a warning associated with it. But backward compatibility gets in the way. /: (But it also used to be worse in that you could not replace the default glob and have it work in a scalar context.)
When you use, in a scalar context, "an operation that would return a list if used in a list context", then you need to look up what that specific operations is going to return (and do) in that scalar context as there is no "standard" answer.
- tye (but my friends call me "Tye")
|
|---|