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

Hello Monks, I have a question about File Handle references coming from a hash value. I have the following code:

my %fh; open (my $ref, ">", "somefile.txt"); $fh{'something'} = $ref; print $fh{'something'} "Hello World\n";

Doing this gives a weird compile error. I know if I add braces like this it will work: print {$fh{'something'}}

but

I'm allowed to do this: print $ref "Hello World\n";

My question is why do I need these braces? I'm storing the $ref in the value portion then referencing it with $fh{'something'}

Thank you

Replies are listed 'Best First'.
Re: printing to a file handle reference from a hash
by GrandFather (Saint) on Oct 18, 2013 at 22:04 UTC

    From the perlfunc documentation describing "print FILEHANDLE LIST":

    If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead, in which case the LIST may not be omitted:
    print { $files[$i] } "stuff\n"; print { $OK ? STDOUT : STDERR } "stuff\n";
    True laziness is hard work
Re: printing to a file handle reference from a hash
by marinersk (Priest) on Oct 19, 2013 at 05:39 UTC
    To augment GrandFather's most excellent summary, perhaps you can put yourself into perl's headspace for a moment.

    The programmer has given you the following command:

    print

    "Ah," says you, mighty Perl interpreter and compiler that you are, "the programmer wants me to display some output. Let's see what is to be displayed."

    Scanning excitedly into the next parsable text on the line, you see the following:

    $fh{'something'}

    "Ah," says you, practical extractor and reporter that you are, "the programmer wants me to display an element in a hash. Let's go get that value."

    And then you pass out when what you get is a FILE HANDLE, of all things. As the lights fade and dim, you are heard to mutter something which sounds an awful lot like "Nooooo disasssemble Number Five . . . "