Get array length in Perl hash

I have the following:

$data{host} -> [$i] -> {someotherstuff} 

How can I get the length of the array where [$ i]?

+6
perl
source share
3 answers
 $length = scalar( @{ $data{host} } ); 
+14
source share

Answer added based on msw comment :

 use autobox::Core; # ... $data{host}->length; 

This works the same as Cfreak's answer, with the exception of the much less complex syntax, by using a module.

I have the thesis that most legitimate complaints about Perl can simply be answered with "This is not necessarily so!" and satisfied with the brief CV from CPAN.

+1
source share

If you want to use the last index, you can use: $ # @ {$ data {host}}

Obviously, the length of the array is the last index + 1. Use this notation when it is more difficult to achieve a scalar context or when you specifically want a length of-1. For example:

0 .. $ # {$ data {host}} # returns a list of all array indices

Sometimes useful.

0
source share

All Articles