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,


In reply to Re^3: Summing numbers in a file by Athanasius
in thread Summing numbers in a file by pvfki

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.