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

Removing Elements without Storing Them - 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

You might not wish to store the elements you removed while using splice(). It takes up memory, and can equate to more code and variables floating around than you really want. Here is how you remove elements without storing them:


#!/usr/bin/perl

@KoolAidFlavors = (@KoolAidFlavors, 'Grape ','Cherry ','Watermelon

','Fruit-Punch ','Orange ');

print @KoolAidFlavors;

print "\n\n";

splice(@KoolAidFlavors, 1,2);

print @KoolAidFlavors;

print "\n\n";

Here we create the @KoolAidFlavors list and add values to it. Next we print out the list, then use splice() to remove the two elements that follow the first element. Finally we print @KoolAidFlavors again, showing that we extracted some data from it. Here is the result:

  Grape Cherry Watermelon Fruit-Punch Orange

  Grape Fruit-Punch Orange

You can also remove items using a null list:


#!/usr/bin/perl

@KoolAidFlavors = (@KoolAidFlavors, 'Grape ','Cherry ','Watermelon

','Fruit-Punch ','Orange ');

print @KoolAidFlavors;

print "\n\n";

splice(@KoolAidFlavors, 1,2,());

print @KoolAidFlavors;

print "\n\n";

Which gives us the same result as above.



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