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 ;}