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

If I stick a file handle into a hash, is there a way to read from the filehandle ala <$handle> without copying the file handle to a scalar first? Here's some code...

#! /usr/bin/perl -w -T use strict; # assuming 'foo' exists open( my $handle, '<', 'foo' ); my %hash = ( handle => $handle); # prints out GLOB(0x9d2cc28) while( <$hash{handle}> ) { print; } my %worse_yet = ( hash => \%hash ); # won't compile while( <$worse_yet{hash}->{handle}> ) { print; } # I tried *{$worse_yet{hash}->{handle}} and it didn't work either

Replies are listed 'Best First'.
Re: Using File Handle in hash
by ikegami (Patriarch) on Jun 30, 2009 at 20:49 UTC
    That usage of <> is a shorthand for readline. If you switch to readline it still adds to the defined check and the assignment to $_.
    $ perl -MO=Deparse -e'while (<$fh>) {}' while (defined($_ = <$fh>)) { (); } -e syntax OK $ perl -MO=Deparse -e'while (readline($fh)) {}' while (defined($_ = <$fh>)) { (); } -e syntax OK
Re: Using File Handle in hash
by Fletch (Bishop) on Jun 30, 2009 at 20:17 UTC

    Quoth the docs for 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"; print { $OK ? STDOUT : STDERR } "stuff\n";

    Update: Duur, read not write. You want readline (readline( $hash{handle} )). Ignore that first part.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.