Magicked
Magicked

Reputation: 647

Get the length of an array within a Perl hash

I have the following:

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

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

Upvotes: 9

Views: 7430

Answers (3)

Uri London
Uri London

Reputation: 10797

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.

Upvotes: 2

daxim
daxim

Reputation: 39158

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.

Upvotes: 1

Cfreak
Cfreak

Reputation: 19309

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

Upvotes: 17

Related Questions