Robert P
Robert P

Reputation: 15968

Should I use a lexical directory handle with opendir in Perl?

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

opendir(my $dh, $some_dir) || die "can't opendir $some_dir: $!";

as the example.

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

Upvotes: 5

Views: 702

Answers (3)

brian d foy
brian d foy

Reputation: 132802

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.

Upvotes: 3

Adam Bellaire
Adam Bellaire

Reputation: 110489

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

Upvotes: 4

ire_and_curses
ire_and_curses

Reputation: 70152

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

Upvotes: 10

Related Questions