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

You missed the most important, biggest difference between them: glob gives you back a list, but opendir gives you a directory handle. You can pass that directory handle around to let other objects or subroutines use it. With the directory handle, the subroutine or object doesn’t have to know anything about where it came from, who else is using it, and so on:

 sub use_any_dir_handle {
      my( $dh ) = @_;
      rewinddir $dh;
      ...do some filtering...
      return \@files;
      }

With the dirhandle, you have a controllable iterator where you can move around with seekdir, although with glob you just get the next item.

As with anything though, the costs and benefits only make sense when applied to a certain context. They do not exist outside of a particular use. You have an excellent list of their differences, but I wouldn’t classify those differences without knowing what you were trying to do with them.

Some other things to remember:

  • You can implement your own glob with opendir, but not the other way around.

  • glob uses its own wildcard syntax, and that’s all you get.

  • glob can return filenames that don’t exist:

    $ perl -le 'print glob "{ab}{cd}"'
    

Leave a Comment