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

Dear Wise Ones,

I've written a bit of code that opens a tab delimited text file, parses it, and stuffs it into an array of anonymous hashes. This works fine.

And while I can access any single value form any hash in the array with

$arrayOfHashes[$i]]{$key}

I'm having trouble plucking one of those anonymous hashes from the array and putting it into its own hash. The following bit of code does not work
my %tempHash = $arrayOfHashes[0] ; my @tempKeys = keys %tempHash ;
nor does

my @keys= keys @arrayOfHashes[$i]

I get the error: Reference found where even-sized list expected

Whats the trick to plucking one entire hash from an array so that I can store it in its own hash or use hash functions (such as keys on it?

- Paul

Replies are listed 'Best First'.
Re: Retrieving an anonymous hash
by Limbic~Region (Chancellor) on Mar 18, 2004 at 18:27 UTC
Re: Retrieving an anonymous hash
by TomDLux (Vicar) on Mar 18, 2004 at 18:43 UTC

    I wonder whether you really want to move it to it's own hash. That involves making a copy of the anonymous hash in the AoH. I would suggest what you want is to assign ( to a scalar or to some other object ) a referencec to the anonymous hash, so you can manipulate it without involving a lengthy addressing procedure:

    my $hashRef = $arrayOfHashes[0]; my @hashKeys = keys %$hashRef; # or more realistically ... for my $key ( keys %$hashRef ) { something involving $hashRef->{$key}; }

    --
    TTTATCGGTCGTTATATAGATGTTTGCA

Re: Retrieving an anonymous hash
by NetWallah (Canon) on Mar 18, 2004 at 20:07 UTC
    Following up on what TomDLux said, another way of not copying the hash is to use type globs.
    #Turn OFF use strict local *tempHash = $arrayOfHashes[0] ; # Now you can access $tempHash{whatever}

    Offense, like beauty, is in the eye of the beholder, and a fantasy.
    By guaranteeing freedom of expression, the First Amendment also guarntees offense.

      #Turn OFF use strict
      Manipulating typeglobs is perfectly legal under strict, it's trying to treat strings as typeglobs thats illegal.
        Actually you need to turn OFF strict when you USE the local variable, otherwise, you get
        Global symbol "$x" requires explicit package name at blah ...

        To minimize exposure, it should be coded thus:

        no strict qw(vars); ## Accessing code here ... use strict qw(vars);

        Offense, like beauty, is in the eye of the beholder, and a fantasy.
        By guaranteeing freedom of expression, the First Amendment also guarntees offense.