Is it preferable to use lexical dirhandles in Perl?

file-io, perl

Solution

I'm guessing you're asking about using a lexical variable (`opendir(my $dh, ...)`) instead of a named glob (`opendir(DH, ...)` aka `opendir(*DH, ...)`).

Lexical variables are scoped to a block or file, while named globs are global. That means that `opendir(DH, ...)` is to `opendir(my $dh, ...)` as `our $x` is to `my $x`.

In programming, you always want to use the smallest scope possible, so lexical variables are usually the better choice.

Problem

Chapter 10 of Perl Best Practices recommends not using baseword filehandles but instead using indirect filehandles assigned to a lexical variable when opening a file. Similarly, when opening a directory, is it also best to use an indirect dirhandle assigned to a lexical variable instead of a bareword dirhandle? Edit I don't consider this a simple "opinion" type of question as this goes to improving the robustness of my code using published recommended practises.

Original source