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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access