DavidFerrington has asked for the wisdom of the Perl Monks concerning the following question:

I'm sure this is simple, but I just can't figure it out, I've looked at dereferencing and still don't get it. I have opened a file with open and stored the filehandle in a hash, now I want to print to the filehandle, but using the following code gives syntax error, presumably because the parser doesn't know the hash value is a filehandle.
our %hash;
...
open_file();
...
write_to_file();
...
sub open_file {
  open $hash{fh}, '<', 'myfile';
}
sub write_to_file {
  print $hash{fh} 'some line of data\n";
}
however, if I change the write_to_file sub to be
sub write_to_file {
  my $fh = $hash{fh};
  print  $fh 'some line of data\n";
}
that works, but I'd far rather do it the 'proper' way
-- David

Replies are listed 'Best First'.
Re: using a filehandle stored in a hash
by FunkyMonk (Bishop) on Mar 28, 2010 at 11:08 UTC
    Wrap the hash in a pair of braces:

    my %hash; open $hash{fh}, '>', 'foo' or die $!; print {$hash{fh}} "foo"; # ^ ^


    Unless I state otherwise, all my code runs with strict and warnings
      DOH!
      so simple - I didn't think of that - thank you
      -- David
Re: using a filehandle stored in a hash
by toolic (Bishop) on Mar 28, 2010 at 12:52 UTC
    You already have the solution, but here is how to get the solution: read the documentation of print:
    Note that if you're storing FILEHANDLEs in an array, or if you're using any other expression more complex than a scalar variable to retrieve it, you will have to use a block returning the filehandle value instead:
    print { $files[$i] } "stuff\n";