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

LS,

I ran into a problem I've run into before. I have been coding in LPC for entirely too long, and it's a standard range selection there to use [4..-1] to reference array (or string) slices.

Is there any reason why in perl [-1] gives me the last element of an array, but [4..-1] doesn't give me the 5th through last element as a slice?

(And yes, I do know that [4..$#arr] works, however that isn't the question :)

Splutty.

ps. Sorry about the silly formatting, let me see if I can fix that.

20060815 Janitored by Corion: Added formatting, code tags, as per Writeup Formatting Tips

Replies are listed 'Best First'.
Re: Reasoning behind -1 not working in slices?
by davidrw (Prior) on Aug 15, 2006 at 12:41 UTC
    Quoting from perlop:
    Binary ".." is the range operator, which is really two different operators depending on the context. In list context, it returns an array of values counting (up by ones) from the left value to the right value. If the left value is greater than the right value then it returns the empty array.

    side note: if being destructive is ok, then @foo = splice(@list,4)
Re: Reasoning behind -1 not working in slices?
by Limbic~Region (Chancellor) on Aug 15, 2006 at 12:46 UTC
    Splutty,
    To add to the previous answer(s), -1 is not a macro to say "the last element". It is an offset. Perl allows you to use negative offsets to access an array from either end. The range operator (see perlop) only works in ascending order though Perl 6 will greatly increase your flexibility.

    Assume for a second you have a 4 element array and you want to take the slice 2 .. -2.

    2 with positive offset my @array = (1, 2, 3, 4); -2 with negative offset
    Don't you think it violates the principal of least suprise to expect Perl to realize you are taking an array slice, calculate the positive index of the negative offset and then create an ascending range for you?

    Update: Phrased the last question better.

    Cheers - L~R

      I understand the principle of why it doesn't work. However I maintain that it would not be unlogical to have as a 'last element' identifier a negative number going from the end of the array.

      But since perl doesn't actually use the list as array indexing, but to actually build a list, which is then subsequently used to get a slice from the array, this probably won't be possible/easy.

      Thanks for all the replies :) It has greatly improved my understanding of slice definitions.

Re: Reasoning behind -1 not working in slices?
by jhourcle (Prior) on Aug 15, 2006 at 11:38 UTC

    In perl, '..' generates a range between two values. I don't think it actually has the array context at the point that it's generated, so [4..-1] generates the same as:

    my @indexes = (4..-1); #empty list @array[@indexes];