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

Hi, I am having problem with using a file handle in a hash. For example:

############################### my %FileHandles; my $Dir = '/tmp'; my $FileName = 'test'; open $FileHandles{$Dir}{$FileName}, "$Dir/$FileName" or die "Cannot op +en $Dir/$FileName: $!"; while (<$FileHandles{$Dir}{$FileName}>) { print $_; } $FileHandles{$Dir}{$FileName}->close; ###############################

The script above doesnt' print the contents in the test file. I only get a line like "GLOB(0xdfa4440)" instead. Any idea?

Replies are listed 'Best First'.
Re: Problem with using file handle in hash
by GrandFather (Saint) on Jun 24, 2016 at 04:29 UTC

    while (<$FileHandles{$Dir}{$FileName}>) doesn't work. You must use a simple variable. The fix is:

    ... my $fh = $FileHandles{$Dir}{$FileName}; while (<$fh>) { print $_; }
    Premature optimization is the root of all job security
      thanks for the prompt reply. Simple variable works!
Re: Problem with using file handle in hash
by BrowserUk (Patriarch) on Jun 24, 2016 at 05:06 UTC

    The diamond operator doesn't like compound variables; but you can work around that by using its function form: readline. This works fine:

    while( readline( $Some{compound}{variable}[1] ) ) { ... }

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice. Not understood.

      I ran into this a few months ago as I wanted to create a dictionary of handles, but somehow, never came across readline. I'm glad this thread came up.

      thanks. this can work around it too!