in reply to Storing open filehandles in a hash

while (<>) { defined $fhs{$conn} or open($fhs{$conn}, '>', "conn-$conn") or die("Unable to create file conn-$conn: $!\n"); print { $fhs{$conn} } $_; }

Replies are listed 'Best First'.
Re^2: Storing open filehandles in a hash
by kovacsbv (Novice) on Nov 20, 2008 at 14:59 UTC
    Can you shed some light on what the braces around $fhs{$conn} do in this case? It must have something to do with the file handle and print string being space separated, but I've been wondering for a while why we need those if we're using anything more complex than $variable_name but don't otherwise.

      See the last paragraph of print's documentation.

      To keep the parser sane, print is very limited as to what it can accept for the file handle argument. It accepts a scalar variable ($fh) or a bare word (FH), and that's probably it unless you wrap the expression in curlies. Inside the curlies can be any Perl expression, including the a hash lookup as desired by the OP.

      print { $fh } ...; print $fh ...; # Shorthand print { FH } ...; print FH ...; # Same thing, but also works under strict 'vars'. print { *FH } ...; print { $a[$i] } ...; print { $h{$k} } ...; print { $o->get_fh() } ...; print { $e ? *STDERR : *STDOUT } ...; etc.