in reply to A question of perlish elegance on array loop

You don't need the extra @{} In there. Just $#{ $array_ref } is what you want (or $#{ $obj->{ array_ref } } from your example).

Update: And seconded, unless you've got good reason to need the index for my $elem ( @{ $obj->{ array_ref } } ) { ... } is more idiomatic.

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: A question of perlish elegance on array loop
by ait (Hermit) on Nov 30, 2007 at 00:44 UTC
    WOW! Many thanks, it works like a charm

    Since perl it usually chokes (not an array ref on...) on object array references like so: foreach(@$obj->{array_ref}) I figured that it would also choke on $#{$obj->{array_ref}} by not recognizing the array ref in the inner reference. That's why I did'nt bother trying and following my instinct (which usually has worked in Perl!) went ahead on the use of $#{@{
    But that looked pretty awkward so I went and searched a lot CPAN code to see if anyone else was using it, and well, you know the rest of the story :)

    I guess I'll have to study a lot on Introspection and Globs to get the answer to that one, huh?

    Update: Hmmm. After re-reading this, I think I have just answered myself: the same way that @{ "casts" to array is the same way $#{ "casts" to array also. Silly me! Thanks again for making me understand this!

      Not really globs, just references. In general wherever you can have a sigil ($@%*) followed by a variable name you can use a BLOCK returning a reference of the appropriate type; e.g. just like @hash{ qw/x y/ } does a hash slice of %hash you can do @{ $hashref }{ qw/ x y / } to slice the hash referred to by $hashref.

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.