http://qs321.pair.com?node_id=592000


in reply to module which tells more warning about FILHANDLE

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; }