O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appending One Array to Another

Problem

You want to join two arrays by appending all the elements of one to the end of the other.

Solution

Use push:

# push
push(@ARRAY1, @ARRAY2);

Discussion

The push function is optimized for appending a list to the end of an array. You can take advantage of Perl’s list flattening to join two arrays, but it results in significantly more copying than push:

@ARRAY1 = (@ARRAY1, @ARRAY2);

Here’s an example of push in action:

@members = ("Time", "Flies");
@initiates = ("An", "Arrow");
push(@members, @initiates);
# @members is now ("Time", "Flies", "An", "Arrow")

If you want to insert the elements of one array into the middle of another, use the splice function:

splice(@members, 2, 0, "Like", @initiates);
print "@members\n";
splice(@members, 0, 1, "Fruit");
splice(@members, -2, 2, "A", "Banana");
print "@members\n";

This is output:

               
                  Time Flies Like An Arrow
               
                  Fruit Flies Like A Banana

See Also

The splice and push functions in perlfunc(1) and Chapter 3 of Programming Perl; the “List Values and Arrays” section of Chapter 2 of Programming Perl; the “List Value Constructors” section of perldata(1)

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required