As an historical aside, note that using the result of evaluating the expression (scalar @ra) - 1 is not quite the same as using an index of -1 or $#array if you have set the array base $[ (which defaults to 0) to be 1 — but don't do that! See $[ in Deprecated and removed variables in perlvar. Assignment to $[ was first deprecated in Perl version 5.12 and has been increasingly constrained in subsequent versions.
c:\@Work\Perl\monks>perl -wMstrict -le
"$[ = 1;
;;
my @ra = qw(zero one two three);
;;
print scalar @ra;
print 0 + @ra;
print $ra[ (scalar @ra) - 1 ];
print $ra[ @ra - 1 ];
print $ra[ @ra ];
print $ra[ -1 ];
print $ra[ $#ra ];
"
Use of assignment to $[ is deprecated at -e line 1.
4
4
two
two
three
three
three
In all cases (and regardless of the array base — but again, don't futz with that):
-
evaluating an array in any scalar context yields the number of elements (or length) of the array;
-
$#array yields the maximum index of the array;
-
negative indices are handled consistently.
Give a man a fish: <%-{-{-{-<
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|