Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does perl only dereference the last index when the range operator is used?

Tags:

perl

I have an array, @array, of array references. If I use the range operator to print elements 1 through 3 of @array, print @array[1..3], perl prints the array references for elements 1 through 3.

Why when I try to dereference the array references indexed between 1 and 3, @{@array[1..3]}, perl only dereferences and prints out the last element indexed in the range operator?

Is there a way to use the range operator while dereferencing an array?

Example Code

#!/bin/perl

use strict;
use warnings;

my @array = ();
foreach my $i (0..10) {
    push @array, [rand(1000), int(rand(3))];
}

foreach my $i (@array) {
    print "@$i\n";
}

print "\n\n================\n\n";

print @{@array[1..3]};

print "\n\n================\n\n";
like image 426
EarthIsHome Avatar asked Jul 22 '15 17:07

EarthIsHome


1 Answers

From perldata:

Slices in scalar context return the last item of the slice.

@{ ... } dereferences a scalar value as an array, this implies that the value being dereferenced is in scalar context. From the perldata quote above we know that this will return the last element. Therefore the result is the last element.

A more reasonable approach would be to loop through your slice and print each individual array reference:

use strict; 
use warnings; 

use feature qw(say);

my @array_of_arrayrefs = (
   [qw(1 2 3)],
   [qw(4 5 6)],
   [qw(7 8 9)],
   [qw(a b c)],
);

foreach my $aref ( @array_of_arrayrefs[1..3] ) {
   say join ',', @$aref;
}
like image 193
Hunter McMillen Avatar answered Nov 15 '22 11:11

Hunter McMillen