views:

133

answers:

3
$HoA{teletubbies} = [ "tinky winky", "dipsy", "laa-laa", "po" ];

How can I find the number of elements in this hash of arrayref(s)? It should return 4.

+12  A: 

Technically, that's not hash of arrays. That's hash of array references. So you should dereference it with @{...} operator and (optionally) force scalar context to convert array into its length.

scalar @{$HoA{teletubbies}}
Pavel Shved
Obligatory mention of http://perlmonks.org/?node=References+quick+reference
ysth
perldsc and perllol use the "hash of arrays", "array of arrays", etc. nomenclature. Anyone who writes `%HoA` probably has just read perldsc. I dislike it myself, but... it's too big to fight ;)
hobbs
+6  A: 

You can get the size of an array in Perl by evaluating it in a scalar context.

E.g., you can do this explicitly like:

my $size = scalar @{$HoA{teletubbies}};

But you can also do it implicitly in this instance:

my $size = @{$HoA{teletubbies}};

And this being Perl, you could also do it like this:

my $size = $#{$HoA{teletubbies}} + 1;

(The # operator returns the last index of an array, so adding one to it will give you its size).

Tom
The last one is extra work and harder to read at a glance. In some cases, there's no real reason to search for "more ways" to do it.
Telemachus
The last one is also deprecated in 5.10.
sebthebert
What `$#` tells you depends on the value of `$[`.
Sinan Ünür
So shouldn't it be: my $size = $#{$HoA{teletubbies}} - $[ + 1;
Adrian Pronk
@Sinan Ünür: but don't use that.
ysth
A: 

If you want to do the entire hash then just add a bit more to it:

my $size= 0 ;
foreach ( values %HoA ) { $size += @$_ }
woolstar