cmac has asked for the wisdom of the Perl Monks concerning the following question:

Where does perl get off wrapping around to the top of the array in a $val = $tiedArray[$i] or if (exists $tiedArray[$i])... if $i happens to be negative??   This behavior is acknowledged here.

If I am doing some kind of subscript computation and my subscript happens to go negative, I want to know about it (by receiving undef) NOW, rather than being given some completely unrelated value from the other end of the array! Fooey!

cmac
www.animalhead.com

Replies are listed 'Best First'.
Re: index wrapping in tied FETCH and EXISTS
by apl (Monsignor) on Feb 04, 2009 at 12:41 UTC
    If I am doing some kind of subscript computation and my subscript happens to go negative, I want to know about it (by receiving undef) NOW
    How about
    my $i = ... some calculation ... if ( $i >= 0 ) { $val = $tiedArray[$i]; } else { # report the problem! }
Re: index wrapping in tied FETCH and EXISTS
by Anonymous Monk on Feb 04, 2009 at 08:17 UTC
Re: index wrapping in tied FETCH and EXISTS
by ikegami (Patriarch) on Feb 04, 2009 at 13:25 UTC
    It's a very useful and commonly used feature.
    sub peek { return $stack[-1]; }
Re: index wrapping in tied FETCH and EXISTS
by cmac (Monk) on Feb 04, 2009 at 15:59 UTC
    Oh.

    If non-tied arrays work that way too, the our NEGATIVE_INDICES=1;I put in my tied array class will come out. Also the underlying direct-call methods for array handling will have to change, in how they handle a negative index.

    The original note came about because I was adapting a test sequence for said direct-call methods to a tied array, and got irked when the tie structure broke a test for "outside the array" (below zero).

    Sorry,
    cmac

      You can reach lower than the start of the array by using an index lower than -@array.

      $ perl -wle'$|=1; @a=qw(a b c); print "$_: $a[$_]" for -@a-1..$#a+1' Use of uninitialized value in concatenation (.) or string -4: -3: a -2: b -1: c 0: a 1: b 2: c Use of uninitialized value in concatenation (.) or string 3:
        To me your test shows that you CAN'T reach lower than the start of the array by using an index lower than -@array. A return value of undef is the only way that perl has to tell you that you're doing something bad. OK, not the only way, but dieing/croaking seems too strong for an out-of-range array index.

        It occurred since my previous note that I shouldn't emulate this behavior in the direct-call routines that underlie my tied arrays, because then a user of a tied array would be faced with two layers of "wrapping around".

        Unless I can figure out how to differentiate a tied call from a direct one. Since tied calls come through a little "dereference wrapper" from my AUTOLOAD routine (its PM thread ended yesterday), this should be possible, but I'm not sure it's worth the overhead.

        cmac
        www.animalhead.com