Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: What array negative number counting means

by AnomalousMonk (Bishop)
on Jul 28, 2020 at 03:06 UTC ( #11119875=note: print w/replies, xml ) Need Help??

in reply to What array negative number counting means

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:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: What array negative number counting means
by Anonymous Monk on Jul 28, 2020 at 04:39 UTC
    Thanks for the clarification.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11119875]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2020-09-28 06:45 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (143 votes). Check out past polls.