Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it preferable to use lexical dirhandles in Perl?

Tags:

file-io

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.

like image 994
Rob Wells Avatar asked Nov 30 '25 20:11

Rob Wells


1 Answers

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.

like image 103
ikegami Avatar answered Dec 07 '25 00:12

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!