note
ChrisS
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.
<p>Let me show you what I mean:
<code>
# 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
$bad = @data - 1;
$still_bad = scalar @data - 1;
$good = $#data;
# what did we find?
print "bad: $bad\n"; # gives 3
print "still bad: $still_bad\n"; # gives 3
print "good: $good\n" # gives 5
</code>
<p>
So I would recommend two things:
<ol>
<li>Don't change the starting index value without a very good reason.</li>
<li>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.)</li>
</ol>
<p>Trying to debug someone else's code when they've changed $[ can be particularly annoying.
1868
1868