Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Pulling Array Out of Hash Reference

by enoch (Chaplain)
on Apr 12, 2004 at 22:38 UTC ( #344558=perlquestion: print w/ replies, xml ) Need Help??
enoch has asked for the wisdom of the Perl Monks concerning the following question:

If I have a reference to a hash, is there anyway to index into the referenced hash via an array and pull out those values that correspond as keys in the array. I know... I know... that was a complex sentence. In code:
my %hash = ( a => 'foo', b => 'bar', c => 'baz', d => 'quux', ); print @hash{'a','d'},"\n"; # correctly prints out "fooquux" my $hashRef = \%hash; # generates error # "Not an ARRAY reference at hashArrayPlay.pl line 16." print @$hashRef->{'a','d'};
I have tried various iterations trying to get it to reference correctly. And, I have read through perldata and perlref trying to find an answer to this. Does anyone have any insight?

Comment on Pulling Array Out of Hash Reference
Download Code
Re: Pulling Array Out of Hash Reference
by kvale (Monsignor) on Apr 12, 2004 at 22:43 UTC
    You are very close:
    print @{ $hashRef->{'a','d'} };
    To satisfy operator precedence, the braces are needed in the array dereference.

    -Mark

      I believe you meant:

      print @{ $hashRef }{'a','d'};

      Your code attempts to deref $hashRef->{join $;,'a','d'} which is undefined.

      antirice    
      The first rule of Perl club is - use Perl
      The
      ith rule of Perl club is - follow rule i - 1 for i > 1

        Blush, a bad test on my part. You are entirely correct.

        -Mark

        Which can also be written as

        print @$hashRef{'a','d'};

        as outlined in references quick reference (which is how I finally figured out that all of this syntax is pretty easy to keep straight).

        But I think I'd stick with

        print @{$hashRef}{'a','d'};

        as being clearer.

        - tye        

Re: Pulling Array Out of Hash Reference
by enoch (Chaplain) on Apr 12, 2004 at 22:44 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://344558]
Approved by Enlil
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (11)
As of 2014-11-24 14:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (141 votes), past polls