Perl array copy example: How to copy an array in Perl

Perl array copying FAQ: Can you share some examples of how to copy a Perl array?

Copying a Perl array is actually so simple it seems like a trick question, but unfortunately it's one of those things that is only easy once you know how to do it. (Personally I find the syntax a little non-standard.)

A Perl copy array example

To copy a Perl array named @array1 to a Perl array named @array2, just use this syntax:

@array2 = @array1;

In other languages that seems more like @array2 is a reference to @array1, but in Perl it's a copy.

To demonstrate that this actually copies the first Perl array, here's a short Perl array copy example script to prove the point:

sub print_arr() {
  my (@arr) = @_;
  foreach $elem (@arr) {
    print "  $elem\n";
  }
}

# create an array using the range operator
@arr1 = qw/cheese pepperoni veggie/;

@arr2 = @arr1;

push @arr1, 'works';

print "array1:\n";
&print_arr(@arr1);

print "\narray2:\n";
&print_arr(@arr2);

This simple Perl script produces the following output:

array1:
  cheese
  pepperoni
  veggie
  works

array2:
  cheese
  pepperoni
  veggie

As you can see, the contents of the two Perl arrays following the copy operation are different.

As a disclaimer, I don't know how this works with more complicated objects, but I've tried this with Perl string arrays and integer arrays, and it worked as shown here with both of those.

Perl array copy example - Summary

I hope this example of how to copy a Perl array has been helpful. As usual, if you have any questions or comments, just leave a note in the Comments section below.