See also: Where in the documentation does it say that while tests readdir for definedness?. (Not a duplicate; just closely related.)
Many people treat the loop below as idiomatic:
while (defined(my $file = readdir($dir)) {
...
}
instead of:
while (my $file = readdir($dir)) {
...
}
because supposedly with the latter version if the filename is just "0" (zero) it should terminate the loop, whereas it returns 'undef' when there are no more files.
However at some point in the past this test for defined()
stopped being necessary - there appears to be special case code that allows the latter version to work regardless.
I'd like to know how this works?
Curiously,if I replace the call to readdir()
with a call to foo()
instead:
sub foo
{
my ($dir) = @_;
return readdir($dir);
}
while (my $file = foo($dir)) {
...
}
then the code does do what I'd expect, and terminate the loop when a file named "0" is found.
(tested with Perl 5.8.9 on MacOS X 10.5.6)