John Refior wrote:
Rob Dixon wrote:
David Newman wrote:
# get files
open(DAT, $lfile) or die("unable to open");
my @Llist = <DAT>;
close(DAT);
You should include the $! variable in the die string so that you know why the
open failed. I suggest
my @llist;
{
open my $fh, '<', $lfile or die "Unable to open '$lfile': $!";
@llist = <$fh>;
}
Am I right in thinking that the braces here perform two functions:
1) Limit the scope of $fh.
Yes, as soon as the scope ends the file is automatically closed.
As far as I can tell from the
documentation ( http://perldoc.perl.org/functions/close.html ), the
block should also contain an additional line expressly closing the
file handle. Like:
close $fh or die "Unable to close $lfile: $!\n";
If you want to automatically close filehandles as they go out of
scope, it looks like IO::File can do that (see
http://perldoc.perl.org/functions/open.html at the end of the page).
As of Perl version 5.8 (or was that 5.6?) you don't have to use a module
to get that functionality.
2) Improve readability - the purpose of these lines is to get values
into the array @llist, let's make it look that way.
Another way to do that:
my @llist = do {
open my $fh, '<', $lfile or die "Unable to open '$lfile': $!";
<$fh>;
};
John
--
Those people who think they know everything are a great
annoyance to those of us who do. -- Isaac Asimov
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/