How to merge two arrays in Perl?
Question
How to merge two arrays in Perl?
Merging two arrays in Perl is a common task and can be done easily using array concatenation. Perl's flexible syntax and its principle of TMTOWTDI (“There’s More Than One Way To Do It”) means you have several options to combine two arrays, depending on what exactly you want to achieve.
Basic Array Concatenation
In Perl, arrays are denoted with the @ sigil, and when you want to concatenate two arrays, you simply list them inside parentheses. This creates a new array that contains all elements of the first array followed by all elements of the second array.
#!/usr/bin/perl
use strict;
use warnings;
my @array1 = (1, 2, 3);
my @array2 = (4, 5, 6);
# Merge arrays by concatenation
my @merged = (@array1, @array2);
# Print merged array
print "Merged array: @merged\n";
When you run this example, the output will be:
Merged array: 1 2 3 4 5 6
Key Concepts Explained
- Sigils:
@before variable names indicates an array. When used in a list context like(@array1, @array2), it expands into the individual elements. - Context: Perl treats variables differently based on context. Here, the arrays inside parentheses produce a combined list.
- TMTOWTDI: You could also use built-in functions like
pushor array slices to merge arrays, but concatenation is the simplest and most readable.
Alternative Approaches
push @array1, @array2;— This appends all elements from@array2directly onto@array1, modifying@array1in place.- Using array slices or loops (less common for simple merges).
# Append @array2 to @array1
push @array1, @array2;
print "Appended array1: @array1\n";
Common Pitfalls
- Remember that
@array1 + @array2is a numeric addition of the array sizes, not concatenation. - Be careful with scalar context. Using
my $merged = (@array1, @array2);will only assign the last element because the list is evaluated in scalar context. - Modifying arrays in place affects the original data—use a new array if you want to keep originals intact.
Summary
The idiomatic way to merge two arrays in Perl is simply:
my @merged = (@array1, @array2);
This straightforward method preserves the order of elements and is easy to understand and maintain. For beginners, this is the best starting point for combining arrays.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 6ms
Merged array: 1 2 3 4 5 6
(empty)