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

number of elements in an array

Status
Not open for further replies.

oinky

Programmer
Oct 29, 2001
45
US
Hi, I know that if you have an array say @foo, to get the number of elements in that array you can do $#foo.
However, I am having trouble doing this with an array that was passed into a function as a pointer. Something like this:


@foo = ("1","2","3");

sub1(\@foo);


sub sub1
{
my ($foo) = @_;

push @$foo , "4";
print $#foo;

}



It keeps giving me -1 for the length of array.
please help thanks.

 
The code prints out '3' for me. Note that $#foo is not the number of indexes in the array. It is the last index of array. You can find the size of an array like this;

$size = @$foo;

 
I dont know why but
$size = @$foo does not work for me. when i print $size, its null.
 
You could also try:
Code:
$size = scalar(@$foo);
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
The scalar function is one I always forget about, good point tsdragon.

I know it is simple but it works and that is the point.

The @foo start at 0 length and propigates from that point. finding the length is easily done by doing this

$size= $#foo+1;

or

print $#foo+1;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top