Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Slice an array, without creating a whole new array

I have a reference to an big array, and some of the elements (from some index to the end) need to get used to insert new rows in a DB.

Is there anyway I can create a reference to part of a bigger array? Or another way I can use a part of a array with DBI's execute_array function, without having Perl copy loads of data in the background?

Here's what I want to do more efficiently:

$sh->execute_array({}, [ @{$arrayref}[@indexes] ]);
like image 295
Jonathon Avatar asked Mar 01 '13 15:03

Jonathon


1 Answers

Array slices return multiple values and have the @ sigil:

my @array = (1, 2, 3, 4);

print join " ", @array[1..2]; # "2 3"

my $aref = [1, 2, 3, 4];

print join " ", @{$aref}[1..3]; # "2 3 4"

A slice will return a list (!= an array) of scalars. However, this is not a copy per se:

my @array = (1, 2, 3, 4);

for (@array[1..2]) {
  s/\d/_/; # change the element of the array slice
}

print "@array"; # "1 _ _ 4"

So this is quite efficient.

If you want to create a new array (or an array reference), you have to copy the values:

my @array = (1, 2, 3, 4);

my @slice = @array[1..2];

my $slice = [ @array[1..2] ];

The syntax \@array[1..2] would return a list of references to each element in the slice, but not a reference to the slice.

like image 152
amon Avatar answered Sep 20 '22 11:09

amon