I understood, that you have two arrays holding the start- and end-indices
respectively of several ranges ($beginingarray[i] .. $endingarray[i])
to be copied or extracted from the bigger array. So, maybe you only need
copies of array-slices (see perldata)?
As Corion suggested, use splice to extract ranges
if you need to consume from the @bigarray.
Maybe it's a more convenient approach to encode your ranges as list of
strings (e.g. @range = qw(20-30 1-5);) or
as Array-of-Array(refs) (e.g. @range = ( [20,30], [1,5] );)
rather than having separate arrays of start- and end-indices?
use strict;
# ranges: 1-5, 20-30, 8-15
my @beginningarray = (1, 20, 8);
my @endingarray = (5, 30, 15);
#Populate: I.E. Atom#X(Magn.Y): A#0(M0), A#1(M0), ... A#30(M3)
my @bigarray = map { "A\#$_(M" . int($_/8) . ")" } 0..30;
# copy: leave @bigarray untouched
sub copy_from_array { #start-idx, end-idx, from-array_ref
my ($startidx, $endidx, $a_ref) = @_;
# suggestion: add range checks
return @{$a_ref}[$startidx .. $endidx];
}
# extract: modify original @bigarray
sub extract_from_array { #start-idx, end-idx, from-array_ref
my ($startidx, $endidx, $a_ref) = @_;
# suggestion: add range checks
return splice @{$a_ref}, $startidx, $endidx - $startidx +1;
}
# example: copy and print ranges
for ( my $i = 0; $i < @beginningarray; $i++ ) {
my ($from, $to) = ($beginningarray[$i], $endingarray[$i]);
print "copy: $from-$to:\n\t";
print join(", ", copy_from_array($from, $to, \@bigarray)), "\n";
}
# When using the extraction-method, you need to reverse sort
# and check for overlapping ranges! I introduced another
# notation to get rid of C-ish for-loops later.
# Reverse-sort intervals by start-index (no overlap-check):
my @ranges = sort { $b->[0] <=> $a->[0] } ([1,5], [20,30], [8,15]);
# example: extract and print ranges
foreach (@ranges) {
my ($from, $to) = ($_->[0],$_->[1]);
print "extract: $from-$to:\n\t";
print join(", ", extract_from_array($from, $to, \@bigarray)), "\n";
}
print "the rest:\n\t", join(", ", @bigarray), "\n";
# A#0(M0), A#6(M0), A#7(M0), A#16(M2), A#17(M2), A#18(M2), A#19(M2)
|