<=> and cmp have nice uses. Just pretend the (-1,0,1) return values are really (2,0,1):
@resp = qw( equal greater less ); print $resp[ $x <=> $y ];

Replies are listed 'Best First'.
Re: Fun With Spaceship
by tadman (Prior) on Mar 29, 2001 at 04:02 UTC
    This particular trick is likely to confuse C programmers who are used to negative array indexes meaning the elements that come before zero, such as they do in the integer number space.

    Perl orients negative offsets from the end of the array, or the nth element, not from the 0th element.

    As such:
    my (@stuff) = qw [ one two three four five ]; print join (',', $stuff[-2], $stuff[2]);
    Returns:     four,three I always wondered what assigning to $x[-1] would do in Perl.

    Further, using a little regression, the following can be derived:
    my (@ans) = qw [ false true ]; print $ans[ !!(assertion) ];
      I always wondered what assigning to $x[-1] would do in Perl.

      So i started playing around with this...

      Works:
      $ perl -e 'my @arr=(1,2,3); $arr[-1]=4; print join " ", @arr, "\n";' 1 2 4 $

      Doesn't work:
      $ perl -e 'my @arr; $arr[-1]=4; print join " ", @arr, "\n";' Modification of non-creatable array value attempted, subscript -1 at - +e line 1. $

      Does this mean that perl does not create the array yet but merely creates a 'variable of type array' when doing my @array ?(kindof like Vector myVector; in java). It would only create the array and start allocating memory to it when you start inserting elements to that array ..


      Jorg

      "Do or do not, there is no try" -- Yoda

        $a[-1] is "the last element of @a". In the failure case, @a has no elements and so has no last element. I suppose you could argue that it should "create the last element". However, what would you have the following do?

        my @a= ( 0, 1 ); $a[-1]= -1; # @a is now ( 0, -1 ) $a[-2]= -2; # @a is now ( -2, -1 ) $a[-3]= -3; # fatal error
        Feel free to submit a patch that does unshift for that last line and that for my @a; $a[-100]= 1 produces @a= (1,(undef)x99). ;)

                - tye (but my friends call me "Tye")
Re: Fun With Spaceship
by MeowChow (Vicar) on Apr 04, 2001 at 11:17 UTC
    Oh yes, here's the technique in action. Nice golfing, donch'a think? :-)
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print