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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ow to determine a multidimensional array's size? hash size? 2

Status
Not open for further replies.

cyan01

Programmer
Mar 13, 2002
143
US
I wonder how to determine the size of a multidemensional array and the size of a hash. For example:

@foo = (
['e11', 'e12' ],
['e21', 'e22' ],
);

print "\$#foo = $#foo\n";

for($i=0; $i<=$#foo; $i++)
{
for($j=0; $j<2; $j++)
{
print "\$i = $i, \$j = $j, $foo[$i][$j]\n";
}
}

The output is
=============
$#foo = 1
$i = 0, $j = 0, e11
$i = 0, $j = 1, e12
$i = 1, $j = 0, e21
$i = 1, $j = 1, e22

Note the inner for loop is hard coded ($j<2), is there a way to tell how many columns in each row?

Also is there a way to find out the size of a hash?

Many thanks!
 
Cyan,

To find the size of any array, you use the $#, as you noted above. To find the size of a multidimensional array, just cast the inner array as so:

my @multiArray = ['a', 'b'], ['c', 'd'];
$innerSize = $#{$multiArray[0]};

Don't know of any easy ways of determining a hash size.

HTH,

Nick


 
While I don't know of any automatic ways to determine the length of a hash, you could write a quite subroutine to do so.

Code:
my $hashcount = &GetHashCount(\%myHash);


sub GetHashCount
{
    my $hash_ref = shift;
    
    my $count = 0;

    foreach $key (keys $%hash_ref)
    {
        $count++;
    }

    return $count;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top