Tuesday 10 December 2019

Arrays and negative indexes in Perl



I am newbie in Perl and I am reading about arrays.
As I understand the arrays expand automatically as needed (cool!)
But I also read that we can use negative indexes to access the arrays in reverse order.
E.g. an array of 3 elements can be accessed as:
$array[0] $array[1] $array[2]
or
$array[-1] $array[-2] $array[-3] (in reverse order).
My question is what happens for values smaller than -3 e.g. $array[-5]?
Does the array expand or something?



Answer



If you read it, the result is the same as reading $array[5] — the value doesn't exist and you get an undef out. Going off the end to the left and going off the end to the right are the same.



If you write it, you get an error. Arrays can only auto-extend to the right.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...