In our last article we talked about lists, going somewhat in-depth on their capabilities. We talked about creating them, printing from them, and even used a slicing technique to add and remove from our lists. In this article we will start off looking at more traditional ways to add and remove from a list, and move on from there.
How To Add and Remove Elements in a List the Old-Fashioned Way
There are several functions in Perl that allow you to add or remove elements from a list. In this next section, we will cover them all. Here they are in a bulleted list to get your lips drooling:
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 left side (or beginning) of a list.
Splice: Used to remove and add elements whose location you specify.
Ahh...Push It...Push it Real Good!
I'll have to admit it: I was in fifth grade and I had formed a new rap band with the menacing name 2Bad4Ya. My teacher at the time, one Mr. Bonner (whose name we made fun of all the time) also knew some people in the industry. So I decided to "borrow" the music to that piece of poetry by Salt N Peppa and add my own lyrics to it. I then proceeded to play it for my teacher, and fortunately I was too dumb at the time to be as embarrassed as I should have been when he chuckled, played with his goatee, ran a hand through his jerri-curls and said, "Uhhh yeah, dat's nice."
As we said in our table above, the push() function can be used to add an item to the right side of a list. But enough talking; here it is in code:
This code creates two lists, the gladiators and new arrays. We assign values to each, and then use the push() function to add the values in our @new list to our @gladiators list, which of course results in:
Nitro Blaze CountFistula TheNutcracker Glutious-Minimus Max Fightmaster
But what if that temp you hired added the wrong name? Or typoed it? Or the person quit? Never fear (unless Hillary Clinton becomes president). To remove that record, or any record, from the right hand side, simply use the pop() function.