Skip to content

[doc] readdir , useless example, not working with "0" directory #22997

Closed
@znik3040

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:

  1. '' - empty string
  2. undef
  3. 0 - zero value
  4. "0" - text with zero char
  5. empty table in scalar context
  6. 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.

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions