Perl Lists: More Functions and Operators (
Page 1 of 5 )
We left off covering the splice() function, which can be used for adding and removing elements from a list. We also spoke about four other functions: pop(), push(), shift(), and unshift(), which are all similar to the splice() function, just not as flexible. In this article, we'll start out by discussing the splice() function in more detail, and learning how to remove more than one element in a list.The last example we discussed in our previous article dealt with removing one element from a list. Here, we will preview briefly the arguments that make up the splice() function, and learn how to add and remove multiple elements in a list with them.
As we stated before, here are the arguments that make up a splice() function:
-
Push: used to add an item to the right side (or end) of a list
-
Pop: a horrible type of music whose name derives from the word popular. Also, used to remove an item from the right side (or end) of a list
-
Shift: used to remove an item from the left side (or beginning) of a list
-
Unshift: used to add an element to the right side (or beginning) of a list
-
Splice: used to remove and add elements whose location you specify
Removing More than One Element in a List
Removing more than one element in a list is pretty similar to removing just one. All you do is change two things: the number of elements you wish to use, and the variable where you will store the removed elements from a scalar to a list. Here it is in code:
#!/usr/bin/perl
@KoolAidFlavors = (@KoolAidFlavors, 'Grape ','Cherry ','Watermelon
','Fruit-Punch ','Orange ');
print @KoolAidFlavors;
print "\n\n";
@bestflavor=splice(@KoolAidFlavors, 1,2);
print @KoolAidFlavors;
print "\n\n";
print @bestflavor;
Here, we have take two elements from the @KoolAidFlavors list and stored them in @bestflavor. Here is the result of the code:
Cherry Watermelon