What does the -1 in the array slice signify? The last element of the array?
Yes. Any negative indices are taken to be the highest position minus the absolute value. So -1 is the last, -2 the second from last and so on. Similarly, negative offsets used in substr, index are offsets from the end of the string, and with splice for arrays.
This is a very pragmatic and useful feature of perl. there are two extensions to the notion that I wish were supportable.
I would like -0 (minus zero) to signify beyond the end of the array or string. This would be useful in some algorithms that use substr or splice to insert things relative to the end of the string or array.
my $s = 'the quick brown fox';
substr($s, 10, 0) = 'light-'; # result: 'the quick light-brow
+n fox'
substr($s, -3, 0) = 'female '; # result: 'the quick light-brow
+n female fox'
substr($s, 0, 0) = 'I saw '; # result: 'I saw the quick ligh
+t-brown female fox'
substr($s, -0, 0) = ' cross the road'; # ' cross the road.I saw the qu
+ick light brown female fox' :(
Unfortunately, in the last example above, the -zero is taken as the same as zero, and the assigned text is prepended to the string rather than appended. There is no syntax available to append to the end of the string using substr. Using -1 would have resulted in 'I saw the quick light-brown fo cross the road.x'. This forces the need to test for special cases:
sub insert_end_relative{
my ($string, $pos, $insert) = @_;
# ADDED the 0 subsequent to Abigail's post below. return $p
? substr($string, -$pos, 0) = $insert
: $string .= $insert;
}
Which could be avoided if perl supported the concept of negative zero.
And the other thing that would be useful, is for 0..-1 to be equivalent to 0..$#array when used in the context of an array slice @array[0..-1] would be slightly nicer than @array[0..$#array] but there are probably two many cases where it would be ambiguous.
Examine what is said, not who speaks.
1) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
2) The only way of discovering the limits of the possible is to venture a little way past them into the impossible
3) Any sufficiently advanced technology is indistinguishable from magic.
Arthur C. Clarke.
|