[Israel.pm] Correct way of taking a slice of a hash reference

Gaal Yahas gaal at forum2.org
Mon Jan 21 00:28:10 PST 2008

On Jan 21, 2008 10:11 AM, Amir E. Aharoni <amir.aharoni at gmail.com> wrote:
> On 21/01/2008, Adam BE <adamb_e at yahoo.com> wrote:
> > Using @$hash_ref{ @keys } I get a "@$hash_ref Not an ARRAY reference" warning in Komodo
> >
> > however I get no warning when running the same code with use strict and use warnings
> > in the Perl debugger.
> The best practice according to the Perl Best Practices book is to use
> @{ $hash_ref }{ @keys }. (Pages 227-229).

Not to start a flame war, but I'd suggest reading that book for ideas
and the discussion that might ensue, not to be taken as gospel truth
about True Style.

> Your code seems to be perfectly good. Maybe Komodo is silly and
> doesn't know about hash slice pretending to be arrays.
> Komodo is not the only tool that disregards this. Perl::Critic warns
> about using %$hash_ref, but not about @$hash_ref.
> (Your question reminded me of my first days of learning Perl. I
> somehow figured out by myself that it makes sense that hash slices are
> accessed as arrays. I don't understand why do so many people complain
> the sigils...)

I think there are two reasons for this.

The first is that you can have:

  my %var = (...);
  my @var = (...);

And later the identifier '@var' doesn't independently identify which
of the two you are talking about -- you need to look a little further
to see if/what kind of subscripting is taking place.

The other reason is that not everything is an object:

  $someref->method;  # works
  @somearr->method; # does not

Of course, there are internal reasons why this makes sense in Perl 5
-- objects are "merely" blessed *references* to data, and references
are by definition scalars. But if you look at how it's done in Perl 6,
the other way won over, the sigil sticks through the variabl's
lifetime, anything may be used as an object and have methods called on
it; and there are signs that this was a notational success.

> --
> Amir Elisha Aharoni
> English -  http://aharoni.wordpress.com
> Hebrew  - http://haharoni.wordpress.com
> "We're living in pieces,
>  I want to live in peace." - T. Moore
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl

Gaal Yahas <gaal at forum2.org>

More information about the Perl mailing list