Why is $#a one less than the actual number of elements in an array?
Doe开发者_StackOverflow社区s anyone knows why $#a
one less than the actually number of elements in an array?
$ perl -we '@a=(1,2);print $#a'
1
That's the index of the last item and since arrays start at zero (unless you're messing around with things that are better left alone), $#a
is one less than the length of the array.
I would imagine that is because it is the index of the last element in the array. Since the array indexing begins at 0, you need to add one to get the total number of elements in an array.
NB: You can also do this to find the count of an array:
@arr = ("one", "two");
$count = @arr;
print $count;
Array @a = ("a","b","c");
Value of $#a = index of last element(=2).
$a[0] = "a";
$a[1] = "b";
$a[2] = "c";
if you want to get number of elements in the array, you can assign the array to a scalar like
$arrayLength = @a;
#(=3)
Hope this helps you
$#array
is used to find the index of the last element in the array.
In the example above it is position 1 - as indexes in arrays start at 0 in perl.
Everyone is telling you what it returns (which you already know), but you asked why it returns what it does.
Unfortunately, it's not really possible to answer why it returns what it does. Maybe because it makes the following easier?
for (0..$#a) {
...
}
精彩评论