3.1.16 spliceing a List into Another List
We can take a sub-sequence of elements in a list and replace them by elements from another list using the splice function. Consider the following program.
Program 3.14
#!/usr/bin/perl
use strict;
$" = ", ";
my @friends = ("Shonna Dyer", "Rich Rogers", "Nicole Nugent", "John Warner",
"Reeves P. Smith", "Jeff Perich", "Susan Worley");
my @newFriends = ("Michael Richter", "Abhijit Bezbarua", "Jugma Bora");
my @noMoreFriends = splice (@friends, 4, 2, @newFriends);
print "My friends are: @friends\n";
print "Some of my friends from years ago are: @noMoreFriends\n";
We use the built-in function splice in this program. It takes four arguments. @friends is the original list. @newFriends is the list whose elements are spliced into @friends. spliceing starts with the element obtained by counting 4 elements over from the beginning of the list to the 5th element. It then removes 2 elements from the list and replaces them with the contents of the list @newFriends. A list containing the removed elements are returned as the value of the splice function. The output of the program is given below. This list of returned values used to set the variable @noMoreFriends. The output of the program is given below.
My friends are: Shonna Dyer, Rich Rogers, Nicole Nugent, John Warner, Michael Richter, Abhijit Bezbarua, Jugma Bora, Susan Worley Some of my friends from years ago are: Reeves P. Smith, Jeff Perich
The first line of output has been broken into two lines for presentation.
It is not necessary to give the fourth argument in a call to splice. It is also possible to make a call without the third argument as well. If the fourth argument which provides the replacement list, is not given, no replacement is done for the removed elements. For example, if in the previous program, we replace the call to splice by the following call
my @noMoreFriends = splice (@friends, 4, 2);
then, the output will change to the following. We have broken the output when necessary to fit the printed page.
My friends are: Shonna Dyer, Rich Rogers, Nicole Nugent, John Warner,
Susan Worley
Some of my friends from years ago are: Reeves P. Smith, Jeff Perich
If we do not provide the last argument, all elements in the original list after the 4th lement are removed. In this case, the output will be the following.
My friends are: Shonna Dyer, Rich Rogers, Nicole Nugent, John Warner Some of my friends from years ago are: Reeves P. Smith, Jeff Perich
