Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

How do I take a slice of a hash reference?

by entropy (Sexton)
on May 15, 2001 at 03:17 UTC ( #80399=perlquestion: print w/replies, xml ) Need Help??

entropy has asked for the wisdom of the Perl Monks concerning the following question: (references)

I can take a slice of an array ref, but not of a hash ref:
my $arr =[1,'a',2,'b']; my $hash={1,'a',2,'b'}; print join ':',(@$arr )[1,2]; print join ':',(@$hash){1,2};
The first print statement works, the second is a syntax error. I also have this problem when taking a slice of an anonymous hash:
print join ':',(1,'a',2,'b')[1,2]; print join ':',(1,'a',2,'b'){1,2};
Again, the first statement works, but the second is a syntax error.

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I take a slice of a hash reference?
by japhy (Canon) on May 15, 2001 at 03:36 UTC
    Here's how:
    @slice = @{$array_ref}[ @idx ]; @slice = @{$hash_ref}{ @keys };
    And there's no easy way to "pretend" a list is a hash. You need to use a hash reference explicitly:
    $scalar = {1, 'a', 2, 'b'}->{$key}; @slice = @{ { 1, 'a', 2, 'b' } }{ @keys };
Re: How do I take a slice of a hash reference?
by tianping (Initiate) on Jun 02, 2011 at 08:40 UTC
    japhy has answered the question, but it's also worth pointing out the solution to the syntax error in your original code. The parentheses alter the priority; so just remove them:
    print join ':', @$hash{1,2};
    More generally, put curly braces around the hash ref expression:
    print join ':', @{$hash}{1,2};

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://80399]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2021-12-08 01:09 GMT
Find Nodes?
    Voting Booth?
    R or B?

    Results (34 votes). Check out past polls.