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?
#!/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";
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With