What reasons are there to prefer glob over readdir (or vice-versa) in Perl?

前端 未结 10 710
野性不改
野性不改 2020-12-01 02:25

This question is a spin-off from this one. Some history: when I first learned Perl, I pretty much always used glob rather than opendir + read

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 03:09

    Here is a disadvantage for opendir and readdir.

    {
      open my $file, '>', 0;
      print {$file} 'Breaks while( readdir ){ ... }'
    }
    opendir my $dir, '.';
    
    my $a = 0;
    ++$a for readdir $dir;
    print $a, "\n";
    
    rewinddir $dir;
    
    my $b = 0;
    ++$b while readdir $dir;
    print $b, "\n";
    

    You would expect that code would print the same number twice, but it doesn't because there is a file with the name of 0. On my computer it prints 251, and 188, tested with Perl v5.10.0 and v5.10.1

    This problem also makes it so that this just prints out a bunch of empty lines, regardless of the existence of file 0:

    use 5.10.0;
    opendir my $dir, '.';
    
    say while readdir $dir;
    

    Where as this always works just fine:

    use 5.10.0;
    my $a = 0;
    ++$a for glob '*';
    say $a;
    
    my $b = 0;
    ++$b while glob '*';
    say $b;
    
    say for glob '*';
    say while glob '*';
    

    I fixed these issues, and sent in a patch which made it into Perl v5.11.2, so this will work properly with Perl v5.12.0 when it comes out.

    My fix converts this:

    while( readdir $dir ){ ... }
    

    into this:

    while( defined( $_ = readdir $dir ){ ...}
    

    Which makes it work the same way that read has worked on files. Actually it is the same bit of code, I just added another element to the corresponding if statements.

提交回复
热议问题