mr. jaggers has asked for the wisdom of the Perl Monks concerning the following question:

Okay, I have an array of hashes, each corresponding to a file. Each hash has a key for a string (filename), the filehandle, and some other comma delimited data.

Dumper prints each hash like:
$VAR1 = { 'fn' => 'test3.dat', 'no' => [ '0', '1', '2', '3' ], 'fh' => bless( \*Symbol::GEN2, 'IO::File' ), 'oo' => [ '1', '2', '4', '8' ] };
I do some stuff for a while, and then at the end I want to close these filehandles.

So, if my array is $files, then I try:
foreach (@files) { $_{fh}->close; }
So, I run the script and perl says:
Can't call method "close" on an undefined value at test.pl line 62.
So, I replace the block with a print Dumper($_{fh}); which then claims that the value is 'undef'.
???
Where did it go?

Replies are listed 'Best First'.
Re: Filehandle in hash value gets lost
by batkins (Chaplain) on Dec 20, 2002 at 02:37 UTC
    perhaps they go away when you "do some stuff." :)

    a little more code might help.

      :P sorry about that... actually it was stupid and I solved it myself five minutes after posting (I already said in a post that I'm an idiot...).

      Actually, I needed to:
      foreach (@files) { $_->{fh}->close; }
      and that basically took care of it, but it looks pretty ugly to me. But then again, I am just learning perl (my resident guru says I still "speak perl with a C accent"). ...sigh... Well, at least I'm trying!

        To make it look more pretty try:

        foreach my $file (@files) { $file->{fh}->close(); }

        Update: Changed close to close() to improve readability.

        ah, it's all good.