Prior to Perl 5.6 (I think that's the version), a filehandle was merely another slot in a typeglob. Typeglobs only exist in symbol tables, so any filehandle was automatically a package variable and the only way to pass them around was to pass typeglobs around. Since, at the time, pretty much the only way to create a filehandle was with the open statement, I can only assume that Larry thought there was no need to have a separate declaration for the filehandle and thus allowed it to run under strict.
However, if you needed to pass around typeglobs, it was cumbersome and error prone, so newer versions of Perl allow lexically scoped filehandles:
open my $fh, $somefile or die $!;
Incidentally, as a matter of good style, it's usually safer to localize the filehandle within a sub to ensure that you don't trample on a similarly named filehandle in the same package:
sub on {
my $file = shift;
local \*F;
open F, $file or die "Couldn't open $file: $!";
}
Cheers,
Ovid
Update: Okay, now I'm a bit confused. I was curious about the behavior of a lexically scoped filehandle and was wondering what Perl thinks it is:
C:\>perl -e "open my $fh, q|< test.txt| or die $!;print ref $fh"
GLOB
GLOB? I don't get it. perlguts says that a scalar can return this value for a filehandle, but if it's lexically scoped, is this really a typeglob? Are there other, unused slots here, or is this just a poor choice of name? (Or is Ovid off in never-never land again?)
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats. |