PDA

View Full Version : countinf list entries ...


enlight
09-18-2002, 08:16 PM
Hi all,

i have written a bubblesort function in php and because getting to know perl i "ported" it to perl.

But one thing is very funny to me.

Definining:

@unsorted = (3,2,5);

and executing a print:

print $#unsorted;

tells me that the array or list has 2 entries. Filling the list with more keys always does the same wired thing:

returns a number which is always one smaller than it should be.

Probably i am using the # wrong or i missed using a special function.

May anyone tell me what went wrong ?

thanks in advance

-enlight

Mouldy_Goat
09-21-2002, 07:34 PM
What $#array actually returns is the number of the last index in an array. It will not necessarily always be less than the number of elements in the array, but almost always is.

So in an array like this:

$array[0] = "foo";
$array[1] = "bar";
$array[2] = "monkey";

$#array would return 2 because that is the number of the last index being used..

Personally when I want the number of elements in an array I use:

scalar @array;

Which forces @array to be interpreted in a scalar context - i.e. returns the number of elemtents in it.


Just as an aside, Perl and PHP both have nice inbuilt sort functions as it is.. you can find out more about the Perl one here (http://www.perldoc.com/perl5.8.0/pod/func/sort.html). Wasn't sure whether or not you knew this, so just thought I'd mention it.

Hope that helps.

enlight
09-22-2002, 10:39 AM
thanks a lot it helped me out a misery.

I knew that there were sorting functions in PHP and Perl, as i'm a php coder for more that 2 years now. But my aim was to write some of them on my own, so i understand the way the different algos are working and handling the numbers.

Thanks for your help anyways,

regards