Perl: cut an array without creating a whole new array

I have a link to a large array, and some of the elements (from some index to the end) should get used to inserting new rows into the database.

Anyway, can I create a link to part of a larger array? Or in another way, can I use part of an array with the execute_array DBI function without having a copy of the data in the background in Perl?

Here is what I want to do more efficiently:

$sh->execute_array({}, [ @{$arrayref}[@indexes] ]);
+5
source share
3 answers
$sh->execute_array({}, [ @{$arrayref}[@indexes] ]);

looks like

sub new_array { my @a = @_; \@a }
$sh->execute_array({}, new_array( @{$arrayref}[@indexes] ));

Pay attention to the purpose, which copies all the elements of the slice. We can avoid copying scalars as follows:

sub array_of_aliases { \@_ }
$sh->execute_array({}, array_of_aliases( @{$arrayref}[@indexes] ));

Now we just copy the pointers ( SV*) instead of the whole scalars (and any line in it).

+4
source

@:

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"

(!= ) . :

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

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

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

, .

( ), :

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

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

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

\@array[1..2] , .

+5

Perl "pass by reference". , , .

execute_array , @_, @array_of_arrays.

. ( , ).

+1

All Articles