On Tue, May 15, 2012 at 05:15:56AM -0500, Peter da Silva wrote:
> On 2012-05-14, at 07:51, David Cantrell wrote:
> > For extra excitement, perl has this nifty feature where you can index
> > from the end of an array using negative numbers:
> >  @array = ('ant', 'bat', 'camel', 'dolphin');
> >  print $array[-1]; # dolphin
> >  print $array[-2]; # camel
> That really _is_ a nifty feature, it makes all kinds of code so much simpler 
> when origin is zero.

Indeed.  It seems like such a little thing, but even in a language where
you know how long your arrays are like you do in perl, $array[-3] for
"the third element from the end" is so much easier to read than
$array[$#array - 2] ($#array is the index of the last element in the
array).

> But it interacts oddly with ANY origin changes. What happens to it when 
> origin is 1? Does it mean array[0] is the last element?

It gets far more exciting than that!

array: [ant, bat, camel, dolphin]

origin: 0    index: 0        ant
origin: 0    index: 1        bat
origin: 0    index: -2       camel
origin: 0    index: -1       dolphin

origin: 1    index: 0        ant
origin: 1    index: 1        ant
origin: 1    index: -2       camel
origin: 1    index: -1       dolphin

origin: -1   index: 0        ant
origin: -1   index: 1        camel
origin: -1   index: -2       camel
origin: -1   index: -1       dolphin

origin: -2   index: 0        ant
origin: -2   index: 1        dolphin
origin: -2   index: -2       camel
origin: -2   index: -1       dolphin

which is All Kinds Of Fucked Up.

I believe that most of what's happening there is accidental.  $[ was
invented for the use of the a2p awk-to-perl translator, awk using 1 as
its array origin and perl using 0 by default, and it was never intended
to be set to anything other than 0 or 1.  Provided that you set $[
to 0 or 1 (or any other positive number) and provided that you never try
accessing any index less than $[, it behaves as you would expect.

-- 
David Cantrell | Hero of the Information Age

I think the most difficult moment that anyone could face is seeing
their domestic servants, whether maid or drivers, run away
  -- Abdul Rahman Al-Sheikh, writing on 25 Jan 2004 at
     http://archive.arabnews.com/?article=38558

Reply via email to