How to copy an array in Perl?
Question
How to copy an array in Perl?
In Perl, copying an array means creating a new array that contains the same elements as the original array, but is a separate data structure. This is important because simply assigning one array to another does not create a distinct copy — it makes the new array a reference to the same underlying data. To properly copy (or clone) an array, you need to create a new array that contains the elements of the original.
Copying Arrays in Perl: Basic Concept
Arrays in Perl are identified by the @ sigil. To copy an array, you can use the feature that extracting an array in list context returns all its elements. Then assigning this list to a new array makes a full copy.
Here is the simplest way to copy an array:
my @original = (1, 2, 3, 4);
my @copy = @original; # Copy by simple assignment (list context)
Now, @copy holds the same elements as @original, but the two arrays are independent. Changing one will not affect the other.
Complete Runnable Example
#!/usr/bin/perl
use strict;
use warnings;
# Original array
my @original = ('apple', 'banana', 'cherry');
# Copy the array
my @copy = @original;
# Modify the copy
$copy[0] = 'apricot';
# Print both arrays to show they are independent
print "Original: @original\n";
print "Copy: @copy\n";
When you run this script, the output will be:
Original: apple banana cherry Copy: apricot banana cherry
This shows that the copy is a separate array and modifications to @copy don’t affect @original.
Perl Concepts Highlighted
- Sigils: Arrays use
@, array elements use$because they are scalars. For example,$array[0]accesses one element. - Context: Assigning an array to another array happens in list context, so the full list of elements is copied.
- TMTOWTDI (There’s more than one way to do it): Besides simple assignment, other ways exist (like using array slices, or
@copy = @original[0..$#original]), but simple assignment is the most straightforward.
Common Pitfalls
- Assigning array references (e.g.,
$copy = \@original) does not copy the array, only creates a new reference to the same data. - Copying multidimensional arrays requires deep cloning (copying nested arrays), which is more advanced and may require modules like
Storableor recursion. - Remember to use strict and warnings to catch potential issues.
In summary, copying a Perl array is most easily done by assigning the original array to a new array variable, which makes a shallow copy of all elements. This works perfectly for simple lists of scalars.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 5ms
(empty)(empty)