Just to add to the points already made. I like to restrict the scope of scalars to the smallest possible scope. I try even harder when that scalar is a lexical file handle where unexpected side effects, in my mind, can be even less desirable.
A happy consequence of this approach means I can be even more lazy. :-)
I often want to load one or more arrays from data from files and later write out to one or more files. I also use the name of the file in the error message so avoiding typing the name of the file twice means putting it in a variable.
Thinking up a name for the file and the file handle 2, 3, 4 or more times? Far too much effort. Screwing the scope of both to the floorboards saves the effort.
Explicitly closing the file handle is for my benefit, Perl would close it anyway as it goes out of scope (although I must admit I don't check for success). I like to a see matching close with every open.
#!/usr/bin/perl
use strict;
use warnings;
my @rawdata;
{
my $file = 'rawdata.txt';
open my $fh, '<', $file
or die "can't open $file to read: $!";
@rawdata = <$fh>;
close $fh;
}
my @exceptions;
{
my $file = 'exceptions.txt';
open my $fh, '<', $file
or die "can't open $file to read: $!";
@exceptions = <$fh>;
close $fh;
}
# crunch the data
my @exceptions_found;
my @exceptions_counted;
{
my $file = 'exceptions_found.txt';
open my $fh, '>', $file
or die "can't open $file to write: $!";
print $fh "$_\n" for @exceptions_found;
close $fh;
}
{
my $file = 'exceptions_counted.txt';
open my $fh, '>', $file
or die "can't open $file to write: $!";
print $fh "$_\n" for @exceptions_counted;
close $fh;
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.