in reply to Propose addition to use warnings?

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

Replies are listed 'Best First'.
Re^2: Propose addition to use warnings?
by perldigious (Priest) on Nov 29, 2016 at 14:19 UTC

    Thanks kcott, I believe the added scoping you show is one of the things haukex had previously alluded to (at least that's how I interpreted his suggestion). As I had previously mentioned, I have a not so great habit of opening all my required input files immediately near the top of all my programs (essentially making all filehandles global) just to make sure they exist. I do this so users can figure out immediately if they forgot a certain input file and don't wait for my program to grind away processing the other ones before the program has to die. As haukex also pointed out, a simple file test would be a better way to go about that, presumably a series of simple -e tests replacing all the opens at the top of my program, and then the more constrained scoping as I open and process each file.

    Just another Perl hooker - will code for food