Take the 2-minute tour ×

Almost universally when people post questions on SO (or elsewhere) about Perl and reading from files, if any code that involves an old-style open

open FH, ">file.txt" or die "Can't open for write, $!";  # OLD way, do not use!

gets yelled at for not using a lexical filehandle. As we all know,

open my $fh, ">", "file.txt" or die "Can't open for write, $!"; # new hotness

is the proper way to open a file handle in modern Perl. What about directory handles? In a few recent SO questions, people have posed questions that involve opendir, and posted code like

opendir DIR, "/directory" or die "Can't get the directory, wtf?! $!"; # ???

The perldoc pages show


as the example.

Should we be suggesting to folks to use a lexical directory handle for opendir as well?

share|improve this question
It would be nice if while(readdir $dir){...} worked like while(readline $file){...} –  Brad Gilbert Oct 2 '09 at 16:26
While in this case, the perldoc example does do it "right", keep in mind that the examples need to stay focused. Periodically, people suggest going through and adding lexical declarations or strict/warnings to the examples; this largely gets shot down because it really obscures the point of example code. So, if the example had been opendir(DIRH, ...), that would not have been an argument against lexical dirhandles. –  ysth Oct 2 '09 at 18:40

3 Answers 3

up vote 10 down vote accepted

Definitely. The argument for lexical filehandles for directories is identical to that for files - scoping to the current namespace.

share|improve this answer

Yes, lexicals are preferred for opendir as well as open.

share|improve this answer

When I get the chance, I will be fixing all of those examples in the perldocs. Learning Perl already uses the lexical handles in the fifth edition.

share|improve this answer

Your Answer


