in reply to lexical vs. local file handles
Do I miss something here? Do you see any pitfalls using this approach?
- When you localize a glob, you're localizing every variable with that name - scalars, arrays, hashes, etc.
- local's effects have dynamic scope, so they effect everything called in that scope, including code that might not be yours. You might step on someone else's globals, or they might step on yours. The major issue is that this is action at a distance: things may break in remote pieces of code, and it may be incredibly hard to connect the problem to the cause. This will not happen with lexicals.
- Bareword filehandles also clash with package names (see also).
- Update from here: open local *HMD, ">", \(my $x) or die $!; print HND "Foo"; close HND; only causes warnings, while open my $hmd, ">", \(my $x) or die $!; print $hnd "Foo"; close $hnd; is a compile-time error.
use warnings; use strict; our $FH = "Hello, World!"; sub FH::awesome { print "<$FH>\n" } FH->awesome; open local *FH, "<", \my $x or die $!; FH::awesome; # => Use of uninitialized value $FH in concatenation (.) or string FH->awesome; # => Can't locate object method "awesome" via package "IO::File"
Though there are good reasons for this, it has a drawback. Filehandles in Perl are special on a syntactical level. The compiler is capable of catching errors like this:
You seem to be naming only a single (IMHO minor) advantage, compared to all the arguments against bareword filehandles. Unless there's something else I'm missing, for me, the arguments against bareword filehandles outweigh those in favor of them.
Instead of using bareword filehandles, you could get into the practice of being explicit about your prints, as in print {$fh} "something\n"; - visually a whole lot more clear. (Update: see also Perl::Critic::Policy::InputOutput::RequireBracedFileHandleWithPrint.)
See also "open" Best Practices.
Update 2: Just to cross-reference this thread to another lexical vs. bareword filehandle discussion: Re^2: Summing numbers in a file
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: lexical vs. local file handles
by jo37 (Deacon) on Apr 18, 2020 at 19:40 UTC | |
by haukex (Archbishop) on Apr 18, 2020 at 19:46 UTC | |
by jo37 (Deacon) on Apr 18, 2020 at 19:52 UTC | |
by chromatic (Archbishop) on Apr 18, 2020 at 20:52 UTC | |
by haukex (Archbishop) on Apr 18, 2020 at 19:54 UTC | |
by jo37 (Deacon) on Apr 18, 2020 at 20:07 UTC | |
| |
by haukex (Archbishop) on Apr 18, 2020 at 21:49 UTC | |
by jo37 (Deacon) on Apr 19, 2020 at 07:52 UTC | |
by haukex (Archbishop) on Apr 19, 2020 at 08:16 UTC | |
by jo37 (Deacon) on Apr 19, 2020 at 08:55 UTC |
In Section
Meditations