in reply to Re^2: Summing numbers in a file
in thread Summing numbers in a file
Hello jcb,
However, I will quibble with this at top-level as in this case: there is no functional difference between the lexical file handles in your example and the traditional global file handles — in both cases, a handle opened at top-level is defined until the end of the script and valid until closed.
Well, for this particular script, that is quite true. And actually, my advice was only meant as indicating good practice in general. However, it is easy to show that a lexical file handle may be a better choice even at the top level:
File example.pl:
package Foo; use strict; use warnings; use autodie; use lib qw( . ); use Foo qw( frobnicate ); open FH, '+<', 'data.txt'; while (<FH>) { print "> $_"; } open my $new_fh, '>', 'more_data.txt'; Foo::frobnicate($new_fh); close $new_fh; open FH, '<', 'data.txt'; print "\n"; while (<FH>) { print ">>> $_"; } close FH;
File Foo.pm:
package Foo; use strict; use warnings; our @EXPORT = qw( frobnicate ); warn "Foo.pm\n"; sub frobnicate { print FH "XYZ\n\n"; } 1;
In example.pl, the intention is to create, and then write to, a new file; but a mistake in Foo.pm causes an existing file to be written-to instead. This occurs without even a warning, because the filehandle in question is global. Giving it lexical scope would highlight the error immediately.
Yes, this is a highly contrived example. But then, why take even remote risks when they can be easily eliminated by the consistent application of good practice?
Hope that’s of interest,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Summing numbers in a file
by jcb (Parson) on Jun 01, 2020 at 02:39 UTC | |
by Athanasius (Cardinal) on Jun 01, 2020 at 07:37 UTC | |
by eyepopslikeamosquito (Archbishop) on Jun 03, 2020 at 10:24 UTC |