Why doesn't Perl file glob() work outside of a loop in scalar context?

后端 未结 4 1068
被撕碎了的回忆
被撕碎了的回忆 2021-02-14 15:49

According to the Perl documentation on file globbing, the <*> operator or glob() function, when used in a scalar context, should iterate through the list of files matching

4条回答
  •  北海茫月
    2021-02-14 16:16

    Here's a way to capture the magic of the <> glob operator's state into an object that you can manipulate in a normal sort of way: anonymous subs (and/or closures)!

    sub all_files {
        return sub { scalar <*> };
    }
    
    my $iter = all_files();
    print $iter->(), "\n";
    print $iter->(), "\n";
    print $iter->(), "\n";
    

    or perhaps:

    sub dir_iterator {
        my $dir = shift;
        return sub { scalar glob("$dir/*") };
    }
    my $iter = dir_iterator("/etc");
    print $iter->(), "\n";
    print $iter->(), "\n";
    print $iter->(), "\n";
    

    Then again my inclination is to file this under "curiosity". Ignore this particular oddity of glob() / <> and use opendir/readdir, IO::All/readdir, or File::Glob instead :)

提交回复
热议问题