Home arrow Perl Programming arrow Page 3 - Perl Lists: More Functions and Operators

Using Splice() to Add and Replace - Perl

We left off covering the splice() function, which can be used for adding and removing elements from a list. We also spoke about four other functions: pop(), push(), shift(), and unshift(), which are all similar to the splice() function, just not as flexible. In this article, we'll start out by discussing the splice() function in more detail, and learning how to remove more than one element in a list.

TABLE OF CONTENTS:
  1. Perl Lists: More Functions and Operators
  2. Removing Elements without Storing Them
  3. Using Splice() to Add and Replace
  4. Adding Values to a List with Splice()
  5. A Few Operators
By: James Payne
Rating: starstarstarstarstar / 2
March 31, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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



 
 
>>> 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: