G'day perldigious,

I looked at this from the perspective of using a lexical filehandle (which is good) but then giving that filehandle global scope (which is less good). Consider this version of your code:

#!/usr/bin/env perl use strict; use warnings; use autodie; { open(my $first_fh, "<", "file1.txt"); my @file1_lines = <$first_fh>; } { open(my $second_fh, "<", "file2.txt"); while (my $line = <$second_fh>) { my @data = my_sub($first_fh, $line); } } sub my_sub { 1 }

All the I/O involving $first_fh is performed in the first anonymous block. On exiting that block, $first_fh goes out of scope, Perl automatically closes it for you, and strict will warn you about it being an argument to &my_sub.

Running that code gives a compile-time error:

Global symbol "$first_fh" requires explicit package name ... line 16. Execution ... aborted due to compilation errors.

Now's the time for that Oops! moment you were hoping for but didn't get. :-)

After s/first/second/ the code compiles cleanly, as evidenced by the runtime error I get:

Can't open 'file1.txt' for reading: 'No such file or directory' ... li +ne 8

As a general rule, use lexical variables in the smallest scope possible.

— Ken


In reply to Re: Propose addition to use warnings? by kcott
in thread Propose addition to use warnings? by perldigious

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.