Insert multiple values from an array into another array
I need to process a large amount of data in arrays with Perl. At certain points, I will need to insert the values of a second array within a primary array. I have seen that splice should normally be the way to go. However, after having researched a bit, I have seen that this function is memory intensive and over time coul开发者_运维技巧d cause a serious performance issue.
Here is basically what I am needing to do -
# two arrays
@primary = [1, 2, 3, 4, 5, 6, 7, 8, 9];
@second = [a, b, c, d e];
Now insert the content of @second into @primary at offset 4 to obtain -
@primary = [1, 2, 3, 4, a, b, c, d, e, 5, 6, 7, 8, 9];
Would using linked lists be the most efficient way to go when I have to handle a primary array which holds more than 2000 elements ?
Note: can anyone confirm that this is the correct way to do it
$Tail = splice($primary, 4);
push(@primary, @second, $Tail);
?
splice @primary, 4, 0, @second;
That is a "correct" way to do it insofaras it works. However, it's probably not the most straight-forward way.
#!/usr/bin/perl -l
use Data::Dump qw(dump);
my @pri = (1..9);
my @sec = ('a'..'e');
print "pri = ", dump(\@pri);
print "sec = ", dump(\@sec);
splice @pri, 4, 0, @sec; ### answer
print "now pri = ", dump(\@pri);
This displays:
$ perl x.pl
pri = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sec = ["a", "b", "c", "d", "e"]
now pri = [1, 2, 3, 4, "a", "b", "c", "d", "e", 5, 6, 7, 8, 9]
which is what you're looking for. Even at 2k elements, you'll probably find this Fast Enough (TM).
# two arrays
@primary = [1, 2, 3, 4, 5, 6, 7, 8, 9];
@second = [a, b, c, d e];
That's not doing what you claim it does. There's an important difference between
# Store a list of values in an array
@primary = (1, 2, 3, 4, 5, 6, 7, 8, 9);
And
# Store a list of values in an anonymous array
# Then store a reference to that array in another array
@primary = [1, 2, 3, 4, 5, 6, 7, 8, 9];
I expect it was just a transcription error, but it's worth pointing these things out in case someone else tries to copy your code.
And, for future reference, please cut and paste code into questions on Stack Overflow. If you retype it there's a chance you'll get it wrong and confuse the people who are trying to help you.
精彩评论