in reply to Re: Fun With Spaceship
in thread Fun With Spaceship

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

Replies are listed 'Best First'.
(tye)Re: Fun With Spaceship
by tye (Sage) on Mar 29, 2001 at 23:27 UTC

    $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")