vroom has asked for the wisdom of the Perl Monks concerning the following question: (arrays)

How do I find the index of the last element in an array?

Originally posted as a Categorized Question.

• Comment on How do I find the index of the last element in an array?

Replies are listed 'Best First'.
Re: How do I find the index of the last element in an array?
by vroom (Pope) on Jan 09, 2000 at 01:05 UTC
You can find it in the special variable \$#arrayname

For example:
```@foo=('b','a','r');
\$lastindex=\$#foo; #in this case 2 the index of 'r'
Re: How do I find the index of the last element in an array?
by chromatic (Archbishop) on Jan 23, 2000 at 05:44 UTC
You can also use negative array indexes:
```my @demo = ("one", "two", "three", "four");
print \$demo[-1];
The result is "four".
Re: How do I find the index of the last element in an array?
by ChrisS (Monk) on Nov 12, 2003 at 14:31 UTC
Be careful... you can change the starting index value to something other than zero. I would not recommend doing so, but if you did, you'd get the wrong value by using scalar.

Let me show you what I mean:

```# change the starting index -- usually not a good idea.
\$[ = 2;

# create a sample array
@data = qw(one two three four);

# try to find the last index value
\$still_bad = scalar @data - 1;
\$good      = \$#data;

# what did we find?
print "good:      \$good\n"         # gives 5

So I would recommend two things:

1. Don't change the starting index value without a very good reason.
2. Use the \$#array_name syntax if you really need the last index value. (Usually, you want the last element, and can just use the negative subscript technique mentioned above.)

Trying to debug someone else's code when they've changed \$[ can be particularly annoying.

Re: How do I find the index of the last element in an array?
by heezy (Monk) on Oct 13, 2002 at 17:38 UTC

Just for any newbies...

Don't forget array indicies start at zero

```
@letterList = ("a", "b", "c", "d");

a is at position 0
b "   "     "    1
c "   "     "    2
...
```

Hope that helps out anyone who fell for the oldest trick in the book

Mark
Hmm....actually, that doesn't really help at all!

If you want to know the index of the last element of an array, do this:

```@letterList = ("a", "b", "c", "d");
#refer to the last array index
#using '\$#array' syntax:

print \$#letterList;