On 7/19/07, Ryan <[EMAIL PROTECTED]> wrote:
What is a lexical file handle?  I'm working my way through Ford's "Perl
Programming for the Absolute Beginner" (2007) and Lee's "Beginning Perl"
(2004), and they both use the FH style of file handle.  Should I do
differently?
snip

Yes, you should use lexical filehandles instead of the old style filehandles.

A lexical filehandle is a filehandle contained withing a scalar
variable*.  Here is one way to create them:

open my $fh, '<', $filename
   or die "could not open $filename: $!";

You can use $fh in all of the same places you use an old style filehandle:

while (<$fh>) {
   #do something
}
close $fh;

There are two major reasons to use them:
1. they are lexical variables and are therefore have all of the
benefits of lexical variables (scoping, easy to pass to functions,
work with closures, etc)
2. they automatically close when going out of scope (as opposed to the
end of the program)

Drawbacks to the old style
1. say you need to open a file inside a long program you haven't
worked on in a while, now, quickly, what filehandles are not in use?
Is FH okay?  Will this close a file already in use?
2. How do you pass a filehandle to function? (with type globs, but it
ain't pretty)
3. Unless you explicitly close them they stay open until the end of the program.


* this is a simplification

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to