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

Slicing Hash References

by Tyke (Pilgrim)
on Mar 01, 2001 at 16:43 UTC ( [id://61539]=perlquestion: print w/replies, xml ) Need Help??

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

I'm trying to use the array slice mechanism. This code
  my %a=('a',1,'b',2,'c',3);
  print for @a{'a','b'};
work fine. However
  my $a={'a',1,'b',2,'c',3};
  print for @a->{'a','b'};
spits out the error message
  Can't coerce array into hash

The quick solution is, of course, to dereference the hash ref into a temporary variable before slicing:

  my $a={'a',1,'b',2,'c',3};
  my %a=%$a;
  print for @a{'a','b'};
Somehow this seems ugly. So does anyone know how I can use the arrow operator to get a hash slice directly from the reference without the need for a temporary.

Replies are listed 'Best First'.
Re: Slicing Hash References
by mirod (Canon) on Mar 01, 2001 at 16:52 UTC

    You might want to use:

    my $a={'a',1,'b',2,'c',3}; print for @$a{'a','b'}; # note the extra $
      Thankyou good Sir. *That's* what I was looking for! I've been working with -> too long to see such a simple solution ;}

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-04-25 22:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found