Perl Programming Page 4 - Perl Lists: More Functions and Operators |
So far we have seen how to remove items from lists and replace items using the splice() function. In this section we will learn to simply add values. It works in a similar manner, only you change the number for the elements to remove to 0, like so: #!/usr/bin/perl @KoolAidFlavors = (@KoolAidFlavors, 'Grape ','Cherry ','Watermelon ','Fruit-Punch ','Orange '); print @KoolAidFlavors; print "\n\n"; splice(@KoolAidFlavors, 1,0,('Pomegranate ','Blueberry ')); print @KoolAidFlavors; print "\n\n"; Here, instead of inserting and replacing the values Cherry and Watermelon with Pomegranate and Blueberry, we will append them to the table. In the line: splice(KoolAidFlavors,1,0,('Pomegranate ','Blueberry ')); we tell the program to insert the two values after the first element. Remember that the 0 tells the program not to replace any elements. If we had written 2,0 then the values would have been added after the second element, and so forth. The result: Grape Cherry Watermelon Fruit-Punch Orange Grape Pomegranate Blueberry Cherry Watermelon Fruit-Punch Orange And just as we can remove values in our @KoolAidFlavors list by using another list, so too, can we add them: #!/usr/bin/perl @KoolAidFlavors = (@KoolAidFlavors, 'Grape ','Cherry ','Watermelon ','Fruit-Punch ','Orange '); @NewFlavors = ('Pomegranate ', 'Blueberry '); print @KoolAidFlavors; print "\n\n"; splice(@KoolAidFlavors, 1,0,(@NewFlavors)); print @KoolAidFlavors; print "\n\n"; The result: Grape Cherry Watermelon Fruit-Punch Orange Grape Pomegranate Blueberry Cherry Watermelon Fruit-Punch Orange It looks the same as before. Which way is best really depends on the situation and your own personal preferences.
blog comments powered by Disqus |
|
|
|
|
|
|
|