Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete elements using grep or map?

Tags:

perl

How do I use grep or map to delete elements from an array or reference to array? I’m having problems using splice to remove one or more elements from a reference to array and would like to see whether grep or map can offer me a better solution.

@removedElements = grep /test/, @array;
like image 491
Yetimwork Beyene Avatar asked May 29 '12 00:05

Yetimwork Beyene


People also ask

How do I pop an array element in Perl?

Perl | Array pop() Functionpop() function in Perl returns the last element of Array passed to it as an argument, removing that value from the array. Note that the value passed to it must explicitly be an array, not a list. Returns: undef if list is empty else last element from the array.

What is Perl splice?

In Perl, the splice() function is used to remove and return a certain number of elements from an array. A list of elements can be inserted in place of the removed elements. Syntax: splice(@array, offset, length, replacement_list) Parameters: @array – The array in consideration.


1 Answers

You are saying "array or reference array" like it was two different things. Which is confusing.

I assume that since you have named your array @removedElements, what you are trying to ask is how to remove the elements from @array and put them in @removedElements.

@removedElements = grep /test/, @array;   
@array           = grep ! /test/, @array;

A simple negation of the test will yield either list. You can also do a loop:

my (@removedElements, @rest);
for (@array) {
    if (/test/) {
        push @removedElements, $_;
    } else {
        push @rest, $_;
    }
}

Which has the benefit of fewer checks being performed.

In order to use splice, you would need to keep track of indexes, and I'm not sure its worth it in this case. It certainly would not make your code easier to read. Similarly, I doubt map would be much more useful than a regular loop.

like image 59
TLP Avatar answered Nov 02 '22 05:11

TLP