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

Why doesn't the print command take a hash value as a file handle? This has always been an annoyance for me:
my %fh; while(<>) { my @record = split; $fh{$record[0]} || open($fh{$record[0]}); my $fh = $fh{$record[0]}; print $fh $_; }
When I try to use $fh{$record[0]} directly, perl complains about syntax errors. My work around works, but I somehow feel dirty afterwards. Is there something that I'm missing?

Thanks in advance,
thor

Replies are listed 'Best First'.
Re: Hash values as filehandles
by jmcnamara (Monsignor) on Apr 30, 2004 at 18:41 UTC

    To use a hash value as a filehandle you need to add another set of braces to create a block around it:
    print {$fh{$record[0]}} $_;

    See print in perlfunc.

    --
    John.

Re: Hash values as filehandles
by chromatic (Archbishop) on Apr 30, 2004 at 18:57 UTC
    Why doesn't the print command take a hash value as a file handle?

    It's very difficult for the parser to know at compile time what the hash value will be. If it's a file handle, you probably want to print to it. If it's not a file handle, you probably want to print it.

    It's probably fixable, but the implications might be kinda scary.

Re: Hash values as filehandles
by blue_cowdawg (Monsignor) on Apr 30, 2004 at 18:42 UTC

        Is there something that I'm missing?

    Looking at your code I'm somewhat perplexed by what you are trying to do since I don't know what's in what variable.

    If $record[0] is supposed to be a file name you might want to consider trying something like:

    use FileHandle; : : hand waving like crazy here.. $fh{record[0]}=new FileHandle $record[0],"r" or die $!; : :
    or some such.

Re: Hash values as filehandles
by ysth (Canon) on Apr 30, 2004 at 21:19 UTC
    The file handle for print goes in what is known as the "indirect object" slot, and follows the requirements for an object: either a simple var (or bareword) or a BLOCK:
    print {$fh{record[0]}} $_;