How can I find the number of elements in hash of an arrayref?
$Ho开发者_如何学CA{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.
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}}
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).
If you want to do the entire hash then just add a bit more to it:
my $size= 0 ;
foreach ( values %HoA ) { $size += @$_ }
精彩评论