Home arrow Perl Programming arrow Page 3 - Perl Lists: More on Manipulation

Unshift My Heart - Perl

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.

TABLE OF CONTENTS:
  1. Perl Lists: More on Manipulation
  2. Pop() Goes Your Data
  3. Unshift My Heart
  4. Splice...It Sounds Like a New Citrus Soda, But It's Not
By: James Payne
Rating: starstarstarstarstar / 4
March 24, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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!



 
 
>>> More Perl Programming Articles          >>> More By James Payne
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PERL PROGRAMMING ARTICLES

- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: