Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Hash slice from a hashref

by Random_Walk (Prior)
on Sep 07, 2006 at 13:46 UTC ( #571686=perlquestion: print w/replies, xml ) Need Help??
Random_Walk has asked for the wisdom of the Perl Monks concerning the following question:

Good $localtime honoured monks

I am having a little bother getting a hash slice from an anonymous hash to which I only have a reference. Without further ado some code

#!/usr/bin/perl -l # this works OK my @l=qw(this is); my %e=qw( this 7 is 6 then 9); print $e{is}; print join "+", @e{@l} # output 6 7+6 #!/usr/bin/perl # yet all my attempts to get this working failed # I tried @{$r->{@l}} @{$r->{@l}} and many more I forget my @l=qw(this is); my $r={qw( this 7 is 6 then 9)}; print $r->{is}; print join "+", @{$r->{@l}} # output 6 # just a blank line above.

What arcane combination of line noise like sigils will bring me enlightenment ?


Pereant, qui ante nos nostra dixerunt!

Replies are listed 'Best First'.
Re: Hash slice from a hashref
by davorg (Chancellor) on Sep 07, 2006 at 13:52 UTC
    print join "+", @{$r}{@l}

    The general rule is that when dealing with references you can replace a hash name with {$ref}. So @hash{@keys} becomes @{$ref}{@keys}.


    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Hash slice from a hashref
by Fletch (Chancellor) on Sep 07, 2006 at 13:51 UTC

    Erm, @{$r->{@l}} is treating the value in $r->{@l} as an arrayref (which isn't going to do anything useful). You mean @{ $r }{ @l }.

      Thanks, I realised it was not going to do anything useful but the required syntax had elluded me completely. Now it is working a treat and I can get some really ugly coding tidied up.


      Pereant, qui ante nos nostra dixerunt!
Re: Hash slice from a hashref
by VSarkiss (Monsignor) on Sep 07, 2006 at 14:02 UTC

      Indeed. :-) busunsl's intro to references is also quite useful.

      IMHO, one of the best discussions of complex data structures, and how to access their innards (using slices and so on), is to be found in Chapter 3. References and complex data structures of perlinter.pdf, available from Perl Training Australia. The OP would probably want the most current version of the course notes, though, which have been reworked into progperl.pdf, available from the same page noted above.



Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://571686]
Approved by Corion
Front-paged by RMGir
[marto]: heh, there's some truth to this
[marto]: youtube warning
Discipulus rh7 is converging towards win, while win converges towards linux..

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2017-12-14 11:06 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (389 votes). Check out past polls.