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 |