Perl Programming Page 3 - Perl Lists: More on Manipulation |
The unshift() function is similar to push except that it adds an item to the front or left side of your list. For this example, let's start with a blank list and fill it with data (you can do the same using push): #!/usr/bin/perl @KoolAidFlavors; unshift(@KoolAidFlavors, 'Grape ','Cherry ','Watermelon ','Fruit-Punch ','Orange '); print @KoolAidFlavors; The result? Grape Cherry Watermelon Fruit-Punch Orange On the Night Shift The shift() function works like the pop() function except it removes the element from the left side of the list. Want to see the code? Too bad: #!/usr/bin/perl @KoolAidFlavors; unshift(@KoolAidFlavors, 'Grape ','Cherry ','Watermelon ','Fruit-Punch ','Orange '); print @KoolAidFlavors; print "\n\n"; $grossFlavors=shift(@KoolAidFlavors); print @KoolAidFlavors; print "\n\n"; print $grossFlavors; Again, we create the @KoolAidFlavors as a null list, then add values to it using the unshift() function. Next we print out the value, then create a new variable named $grossFlavors, which will hold the gross flavors from the list. Of course, the gross flavor must also be the first element for this to work. We use shift() to grab the first element in the list, then print out both the updated list and the variable, resulting in: Grape Cherry Watermelon Fruit-Punch Orange Cherry Watermelon Fruit-Punch Orange Grape Tada!
blog comments powered by Disqus |
|
|
|
|
|
|
|