Scarborough has asked for the wisdom of the Perl Monks concerning the following question:

I've worked with Perl for a couple of years but have just found this
$LENDERCOUNT = $#SORTEDLENDERS;
In some code I am checking. I belive that SORTEDLENDERS is an array. I can't ask the orginal programmer so I am hoping that a monk maybe able to help. $LENDERCOUNT ends up as 1 or -1 when I have run this with -d

update (broquaint): added <code> tags

Thank you all for your Help

20040320 Edit by jeffa: Changed title from 'Whats happening here'

Replies are listed 'Best First'.
Re: What does $#variable mean?
by Limbic~Region (Chancellor) on Mar 19, 2004 at 16:10 UTC
    Scarborough,
    That is Perl making your life easy. The intent is to prevent the programmer from having to keep track of indices.
    my @array = qw(one two three); my $last_index = $#array; # Index of last element (2) my $last_element = $array[ -1 ]; # Value of last element (three)
    And then of course there is push, pop, shift, unshift to make your life easier as well.

    Cheers - L~R

    Update: Some other helpful things to remember
    my $count = @array; # Number of elements (3) $#array = 99; # Extend/Truncate array
Re: What does $#variable mean?
by Rich36 (Chaplain) on Mar 19, 2004 at 16:11 UTC

    $#SORTEDLENDERS indicates that there's an array @SORTEDLENDERS. The $#arrayname syntax holds the index of the last member of an array.

    my @array = ('foo', 'bar', 'baz'); # $#array = 2 # because Perl's array indexes start at 0

    «Rich36»
Re: What does $#variable mean?
by pbeckingham (Parson) on Mar 19, 2004 at 16:11 UTC

    The construct you see is returning the index of the last element in the array, which is one less than the number of elements in the array.

    my @array = (1, 2, 3); print $#array, "\n";
    will print "2".

Re: What does $#variable mean?
by dws (Chancellor) on Mar 19, 2004 at 16:55 UTC
    In case it's slipped by in the answers above, $LENDERCOUNT does not get the count of elements in @SORTEDLENDERS. It gets the last index, which will be one less than the number of elements.

    You may be looking at an off-by-one bug.

    The correct way of getting the count of elements in an array is:

    $LENDERCOUNT = @SORTEDLENDERS;
Re: What does $#variable mean?
by tinita (Parson) on Mar 19, 2004 at 16:13 UTC
    it's the last index of the array @SORTEDLENDERS. so if it has 5 elements, the last index would be 4, as indizes are from 0..4.
    in case the array is empty the last index is -1.
    for details (and exceptions) please refer to perldata
Re: What does $#variable mean?
by pelagic (Priest) on Mar 19, 2004 at 16:14 UTC
    quote from "Learning Perl":
    You can use $#fred to get the index value of the last element of @fred +.

    pelagic

    -------------------------------------
    I can resist anything but temptation.
A reply falls below the community's threshold of quality. You may see it by logging in.