-2

Is there a way to push values into a negative array?

Lets say I'm doing something like this...

my @arr;
push (@arr, "one");
push (@arr, "two");
push (@arr, "three");
$arr[-1] = "neg_one";
$arr[-2] = "neg_two";
$arr[-3] = "neg_three";
for (my $a=-3;$a<@arr;$a++){
    print "Array[".$a."]::".$arr[$a]."\n";
}

# Return
Array[-3]::neg_three
Array[-2]::neg_two
Array[-1]::neg_one
Array[0]::neg_three
Array[1]::neg_two
Array[2]::neg_one

print "Array length: ".@arr."\n";
# Returns 3

So, can you not map a value to a negative index in an array? Seemed to make sense to me that if I wanted to say, plot a value to the left of something, putting it into a negative array would do the trick. So what's the big deal? Am I doing it wrong or is this a very bad practice for reasons I haven't considered?

Thoughts?

Ryan Dunphy
  • 792
  • 2
  • 10
  • 33

1 Answers1

3

A Perl array cannot have elements before index zero. Using indices less than zero accesses the elements relative to the end of the array, so that given

my @arr = qw/ a b c d /

$arr[-1] is d, $arr[-2] is c, etc.

If you wish to store values of a function, then you should transform the values so that they start at zero and have an interval of one. Note that a similar issue arises if you want to store values of f(x) for values of x with intervals of 0.1, except that now the problem is one of scaling rather than offset.

Borodin
  • 126,100
  • 9
  • 70
  • 144
  • 2
    You could also use a hash. That would be less efficient, but would work in the situation where you don't know the largest negative number you'll encounter. // You could also use two arrays: one for the negative indexes (accessed using the negated indexes), and one for non-negative indexes. – ikegami Feb 01 '15 at 21:41