Rob Wells
Rob Wells

Reputation: 37103

Is it preferable to use lexical dirhandles in Perl?

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.

Upvotes: 3

Views: 104

Answers (1)

ikegami
ikegami

Reputation: 385685

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.

Upvotes: 9

Related Questions