As a suggestion to avoid this kind of problem, if you use a lexical variable as a file handle instead of a bareword, when the variable goes out of scope, Perl will automatically close the file for you. e.g.
open my $file, "<", $filename # use lexical variable
open FILE, "<", $filename # use bareword.
So if you have a subroutine;
sub foo {
my ($filename) = @_;
open my $file, "<", $filename or die "blah :$!\n";
while (<$file>) {
# etc
}
# explicit call to close not needed.
}
The file will be closed at the end of the foo subroutine. If you want the file handle then return it.
And if you aren't using a lot of subroutines but want this behavior, simply start a new block.
|