tags:

views:

72

answers:

3

I have the following:

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

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

Thanks!

+8  A: 
$length = scalar( @{ $data{host} } );
Cfreak
and they say Perl syntax is convoluted (says the guy who's been using Perl since v2.x)
msw
I always just tell people that Perl is ahead of it's time :-)
Cfreak
No need for `scalar`. `$length = @{ $data{host} }` would've worked just as well.
Zaid
That did the trick! Thanks!
Magicked
@Zaid: true but I like using scalar because I think it's clearer. I'm a crazy perl programmer who worries about maintainability :-D
Cfreak
If assignment to a scalar variable doesn't imply scalar context strongly enough, I'm not sure who you're expecting to be maintaining your Perl code.
John Siracusa
A: 

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.

daxim
A: 

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.

Uri