Storing Filehandles in Variables
Problem
You want to use a filehandle like a normal variable so you can pass it to or return it from a function, store it in a data structure, and so on.
Solution
If you already have a regular symbolic filehandle like STDIN or
LOGFILE, use the typeglob notation, *FH
. This is
the most efficient approach.
$variable = *FILEHANDLE; # save in variable subroutine(*FILEHANDLE); # or pass directly sub subroutine { my $fh = shift; print $fh "Hello, filehandle!\n"; }
If you want anonymous filehandles, see the
return_fh function below, or use the
new
method from the IO::File or IO::Handle module,
store that in a scalar variable, and use it as though it were a
normal filehandle:
use FileHandle; # make anon filehandle $fh = FileHandle->new(); use IO::File; # 5.004 or higher $fh = IO::File->new();
Discussion
You have many choices for passing filehandles into a subroutine or
storing them in a data structure. The simplest and fastest way is
through the
typeglob notation, *FH
. It may help you to
conceptualize the asterisk as the type symbol for a filehandle. Like
the little colored balls from high school chemistry that stood for
atomic particles, it’s not really true, but it is a convenient
mental shorthand. By the time you understand where this model breaks
down, you won’t need it anymore.
That works cleanly for simple things, but what if you wanted to make an array of filehandles whose names you didn’t know? As shown in Chapter 11, generating anonymous arrays, hashes, ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.