Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays and negative indexes in Perl

Tags:

arrays

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?

like image 967
Cratylus Avatar asked Apr 09 '13 19:04

Cratylus


People also ask

Can arrays have negative index?

JavaScript arrays are collections of items, where each item is accessible through an index. These indexes are non-negative integers, and accessing a negative index will just return undefined . Fortunately, using Proxies, we can support accessing our array items starting from the end using negative indexes.

How do I index an array in Perl?

Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets.

Can arrays have negative index JS?

Unfortunately, JavaScript doesn't offer built-in support for negative array indexes, but we can mimic this ability through proxies.

What is meant by negative indexing?

Negative Indexing is used to in Python to begin slicing from the end of the string i.e. the last. Slicing in Python gets a sub-string from a string. The slicing range is set as parameters i.e. start, stop and step.


2 Answers

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.

like image 126
hobbs Avatar answered Nov 11 '22 06:11

hobbs


You get an undef value if You read the value.

use strict;
use warnings;

my @l = qw(A B C);
print $l[-4];

Output to stderr (program continues to run):

Use of uninitialized value in print at ./x.pl line 7.

Or:

my @l = qw(A B C);
print "undef" if !defined $l[-4];

Output:

undef

If You want to assign a value to it You get an error:

my @l = qw(A B C);
$l[-4] = "d";

Output (program exits):

Modification of non-creatable array value attempted, subscript -4 at ./x.pl line 7.

And actually the interval can be modified. So an array can start any value not only 0.

my @l = qw(A B C);
$[ = -4; # !!! Deprecated
print $l[-4], "\n";
print $l[-3], "\n";

Output:

A
B
like image 44
TrueY Avatar answered Nov 11 '22 04:11

TrueY