Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Sep 2002
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    countinf list entries ...

    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

  • #2
    Regular Coder
    Join Date
    Jul 2002
    Location
    London, UK
    Posts
    126
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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. Wasn't sure whether or not you knew this, so just thought I'd mention it.

    Hope that helps.

  • #3
    New to the CF scene
    Join Date
    Sep 2002
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •