Perl Lists: More Functions and Operators - Removing Elements without Storing Them (Page 2 of 5 )
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.
Next: Using Splice() to Add and Replace >>
More Perl Articles
More By James Payne