Hello zapdos,
To access an element in an array, you specify the index of the element you want. But in Perl (as in C), the first index is not one but zero (0). If the array is named @foo, there is a special Perl syntax to give you the largest index: $#foo. Consider this array:
my @foo = ('bedrock', 'slate', 'lava', 'schist');
# index: 0 1 2 3
As you can see, the array has 4 elements.1 Because the indexes start at zero, these 4 elements have indexes 0, 1, 2, and 3, respectively. The largest index, in this case 3, can be found by accessing the special $#foo variable.
By assigning to $#foo you change the value of its largest index, and thereby re-size the array. For example, if you say $#foo = 2 you make $foo[2] the last element in the array. As a consequence $foo[3], formerly 'schist', ceases to exist. In other words, the array is truncated. If instead you were to say $#foo = 5, you would be adding two new elements to the array, each with an undefined value:
@foo = ('bedrock', 'slate', 'lava', 'schist', undef, undef);
# index: 0 1 2 3 4 5
Now, the first element of the array (in this case with the value 'bedrock') has index 0, as explained above. So if you were to say $#foo = 0, you would be saying “make 0 the largest index into array @foo” — after which the array would contain exactly one element, namely $foo[0] with value 'bedrock'. If you wanted to truncate the array all the way down to zero elements, the largest index would have to be less than zero, so you write $#foo = -1, which produces an empty array. So does assigning an empty list to the array: @foo = (); And that’s why the assignments @foo = () and $#foo = -1 are equivalent.
1You can find the number of elements by putting the array variable into scalar context, e.g., my $number_of_elements = scalar @foo;.
Hope that helps,
| [reply] [Watch: Dir/Any] [d/l] [select] |
Arigato gozaimasu, Athanasius. I love you. ;-)
| [reply] [Watch: Dir/Any] |