See also: Where the documentation says that during readdir testing for definition? . (Not a duplicate, just closely related.)
Many people view the cycle below as idiomatic:
while (defined(my $file = readdir($dir)) { ... }
instead:
while (my $file = readdir($dir)) { ... }
because, presumably, with the latest version, if the file name is β0β (zero), it should break the loop, whereas it returns βundefβ when there are no more files.
However, at some point in the past, this test for defined() ceased to be necessary - it seems that there is a special case code that allows the latest version to work independently.
I would like to know how it works?
Curiously, instead of calling readdir() instead of calling foo() instead of foo() replace
sub foo { my ($dir) = @_; return readdir($dir); } while (my $file = foo($dir)) { ... }
then the code will really do what I expect and end the loop when a file with the name "0" is found.
(tested with Perl 5.8.9 on MacOS X 10.5.6)
perl while-loop readdir defined
Alnitak
source share