开发者

Get the length of an array within a Perl hash

开发者 https://www.devze.com 2022-12-30 20:37 出处:网络
I have the following: $data{host} -> [$i] -> {someotherstuff} How can I get the 开发者_Go百科length of the array where [$i] is?$length = scalar( @{ $data{host} } );

I have the following:

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

How can I get the 开发者_Go百科length of the array where [$i] is?


$length = scalar( @{ $data{host} } );


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

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

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

Sometime useful.


Answer added on account of msw's comment:

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

This works the same as Cfreak's answer, except with much less convoluted syntax, at the cost of using a module.

I have the thesis that most legitimate complaints about Perl can be simply answered with »It does not need to be this way!« and satisfied with short synopsis from CPAN.

0

精彩评论

暂无评论...
验证码 换一张
取 消