Description
Note: bad example in perl core documentation at https://perldoc.perl.org/functions/readdir
In currently available version, bad line:
while (readdir $dh) {
Description
It won't work properly in any situation. For perl, false is:
- '' - empty string
- undef
- 0 - zero value
- "0" - text with zero char
- empty table in scalar context
- empty hash table inscalar context
Except above, value is interpreted as true.
Example code for verification true/false, no one should be printed:
use 5.010;
say "undef" if undef;
say "empty" if '';
say "0" if 0;
say '"0"' if "0";
my @sometable=();
my %somehash;
say "empty table" if @sometable;
say "empty hash" if %somehash;
when readdir function reads directory or file name "0", in boolean context it is false. finally. after reading "0" by readdir, it returns false to while loop.
But readdir after the last element, returns undef. Then full working version should be corrected to:
while (defined readdir $dh) {
please modify documentation, because this is trap for unwary programmers.
Note, I usually use pragmas warning and strict, and do not use default assigment to $_ variable. Then that line i modify into version:
while (defined my $item=readdir $dh) {
and working with named variable.