Perl Programming Page 3 - Perl Lists: More Functions and Operators |
We can also use splice() to add and replace elements in an array. Let's say we want to get rid of two flavors from our list, and replace them with two others: #!/usr/bin/perl @KoolAidFlavors = (@KoolAidFlavors, 'Grape ','Cherry ','Watermelon ','Fruit-Punch ','Orange '); @rem = ('Pomegranate ', 'Blueberry '); print @KoolAidFlavors; print "\n\n"; splice(@KoolAidFlavors, 1,2,(@rem)); print @KoolAidFlavors; print "\n\n"; This code creates the @KoolAidFlavors list, adds a value to it, and then creates the @rem list, adds values to it, and prints out the value of KoolAidFlavors. Next we use splice() to replace the two elements following the first element with the values in the @rem list. When we run this program, we get the following print-out: Grape Cherry Watermelon Fruit-Punch Orange Grape Pomegranate Blueberry Fruit-Punch Orange Note that we don't need to use a list to add and replace values in our @KoolAidFlavors list: #!/usr/bin/perl @KoolAidFlavors = (@KoolAidFlavors, 'Grape ','Cherry ','Watermelon ','Fruit-Punch ','Orange '); print @KoolAidFlavors; print "\n\n"; splice(@KoolAidFlavors, 1,2,('Pomegranate ','Blueberry ')); print @KoolAidFlavors; print "\n\n"; This gives us the same result as above: Grape Cherry Watermelon Fruit-Punch Orange Grape Pomegranate Blueberry Fruit-Punch Orange
blog comments powered by Disqus |
|
|
|
|
|
|
|