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

THANK YOU EVERYONE FOR THE GREAT REPLIES. I must go commune with myself now since it's truly perplexing when one must derefernece and when not to, and when the dereference is implicit.

==========

original question Below:

Commonly one can index out multiple keys simultaneously from a hash like this:

my (%H) = (1,100,2,200,3,300); @A= @H{ (1,3) };

@A now contains (100,200)

But how do I do this when I have not the Hash itself but a reference to the hash?

I want to be able to write something like this:

my $Href = {1 => 100,3 =>300}; @A = @{$Href}->{ (1,3) };

But that does not work.

It would be crazy to reconsitutute the hash (if the hash is enormous) so I don't consider the following a viable option:

$Href = {1 => 100,3 =>300}; %H = %{$Href}; @A = @H{ (1,3) };

The following does work but it is a hideous kludge I think should not be neccessary:

$Href = {1 => 100,3 =>300}; my @A; { local %G; *G = $Href; @A = @G->{ (1,3) } }

Yuck...

SO what's the right way to slice index a a hash reference?

Code tags added by GrandFather

Replies are listed 'Best First'.
Re: Looking up an array of keys with a Hash reference
by bobf (Monsignor) on Sep 25, 2006 at 04:13 UTC

    It looks like you're trying to dereference twice (@{$Href}->{ (1,3) }). Try this instead:

    my @A = @{ $Href }{ 1, 3 };

    I asked a similar question a while ago. The responses in that thread may be of interest, especially if you have more complex data structures.

    HTH

Re: Looking up an array of keys with a Hash reference
by grep (Monsignor) on Sep 25, 2006 at 04:09 UTC
    You do it the same way you did for the non-ref hash.
    my (%H) = (1,100,2,200,3,300); @A= @H{ (1,3) }; #BECOMES my $H = { 1 => 100, 2 => 200, 3 => 300}; my @A = @{ $H }{1,3};
    So other than adding the curlys for the dereference it's the same.


    grep
    Mynd you, mønk bites Kan be pretti nasti...
Re: Looking up an array of keys with a Hash reference
by NetWallah (Canon) on Sep 25, 2006 at 05:24 UTC
    The '@' will bind to the '$Href' even without the braces.
    my @A = @$Href{ 1, 3 };

         "For every complex problem, there is a simple answer ... and it is wrong." --H.L. Mencken

Re: Looking up an array of keys with a Hash reference
by jwkrahn (Abbot) on Sep 25, 2006 at 04:10 UTC