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] ]);
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.
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