Suppose I have 2 arrays like mentioned below
@a1 = ("Vinay", Raj, harry);
@b1 = ("dude","rock");
After merging I want to have result like this
[
Vinay
dude
Vinay
rock
Raj
dude
Raj
rock
harry
dude
harry
rock
]
basically I want to merge the each index values of array1 to all the index values of array2.
Adding to the above question I have another query.
For the same question above how to merge 2 arrays at particular array index. For example I have 2 arrays of each 160 elements, now I want to merge array at every 5th element in sets, is that possible?
Concatenating Arrays in PerlUse the built-in push() function to add one array to the end of another.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
Perl Array join() FunctionThe Perl programming language join() function is used to connect all the elements of a specific list or array into a single string using a specified joining expression. The list is concatenated into one string with the specified joining element contained between each item.
Here is one way to do it. May not be the best perl syntax, though. The double for loop means you will be pushing every combination of the two arrays into the merged array. I've tried to set it up so that the result is in the order you specified in the question.
Given two arrays arr1 [] and arr2 [], we need to combine two arrays in such a way that the combined array has alternate elements of both. If one array has extra element, then these elements are appended at the end of the combined array. Recommended: Please try your approach on {IDE} first, before moving on to the solution.
This step take O (n1 * n2) time. We have discussed implementation of above method in Merge two sorted arrays with O (1) extra space. Method 2 (O (n1 + n2) Time and O (n1 + n2) Extra Space) The idea is to use Merge function of Merge sort . Create an array arr3 [] of size n1 + n2. Simultaneously traverse arr1 [] and arr2 [].
This join () function in Perl works completely opposite to the split () function as this breaks the given single string into an array of elements along with specified separators in Perl.
Just make a new array:
my @merged = (@a1, @b1);
Here's a complete example:
my @a1 = ("foo", "bar");
my @a2 = ("baz", "spam");
my @merged = (@a1, @a2);
print $merged[3]; #=> "spam"
EDIT: I missed the ordering requirement. You just need to zip
them together, which you can do with List::MoreUtils
:
use List::MoreUtils qw(zip);
use Data::Dumper qw(Dumper);
my @a1 = ("Vinay", "Raj", "harry");
my @a2 = ("dude", "rock");
my @merged = zip(@a1, @a2);
print Dumper(\@merged);
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