Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Size of arrays in a hash

Status
Not open for further replies.

fagga

Programmer
Jun 26, 2002
28
DE
Hello there,

I have a hash of arrays so that I can get my values like this:
my $array_value = $hash{'key'}[0];

My question: How can I find out how many elements the array has? Usually I do this with scalar():
my $size_of_array = scalar(@array);
But this one doesn't work:
my $size_of_array = scalar(%hash{'key'});

Do I have to go through every element of the array in $hash{'key'} and count up while it is defined?

Thanks and greetings,
fagga
 
Well, I just read to few documentation. The solution is:
$hash{'key'} is a reference to an array and I have to dereference it, if I want to use the array. This is done by curly brackets and a @.

$ref_to_array = $hash{'key'};
@array = @{$hash{'key'}};

Anyway, thanks to all the people who would have helped me.
 
You can still use [tt]scalar[/tt], like:
[tt]my $size_of_array = scalar(@{$hash{'key'}});[/tt]
 
For example:
Code:
%hash = (
  key1 => [ 1,2,3 ],
  key2 => [ 1,2,3,4 ],
  key3 => [ (1..200) ],
);

foreach $key (sort keys %hash) {
  printf "%s points to array of length %d\n", $key, scalar(@{$hash{$key}});
}
Cheers, Neil :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top