Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
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?

Replies are listed 'Best First'.
Re: Pulling Array Out of Hash Reference
by enoch (Chaplain) on Apr 12, 2004 at 22:44 UTC
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

        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        

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

        -Mark

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
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 having an uproarious good time at the Monastery: (5)
As of 2023-09-27 07:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?