Why does perl only dereference the last index when the range operator is used? -
i have array, @array, of array references. if use range operator print elements 1 through 3 of @array, print @array[1..3], perl prints array references elements 1 through 3.
why when try dereference array references indexed between 1 , 3, @{@array[1..3]}, perl dereferences , prints out last element indexed in range operator?
is there way use range operator while dereferencing array?
example code
#!/bin/perl  use strict; use warnings;  @array = (); foreach $i (0..10) {     push @array, [rand(1000), int(rand(3))]; }  foreach $i (@array) {     print "@$i\n"; }  print "\n\n================\n\n";  print @{@array[1..3]};  print "\n\n================\n\n";      
@{@array[1..3]} strange-looking construct. @{ ... } array dereference operator. needs reference, type of scalar. @array[ ... ] produces list.
this 1 of situations need remember rule list evaluation in scalar context. rule there no general rule. each list-producing operator own thing. in case, apparently array slice operator used in scalar context returns last element of list. @array[1..3] in scalar context same $array[3].
as have noticed, not useful. array slices aren't meant used in scalar context
if want flatten 2-dimensional nested array structure 1-dimensional list, use map:
print join ' ', map { @$_ } @array[1..3]   you still use range operator slicing. need kind of looping construct (e.g. map) apply array dereference operator separately each element of outer array.
Comments
Post a Comment