How to remove elements using grep or map?

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

 @removedElements = grep /test/, @array; 
+8
perl
source share
3 answers

You say "array or reference array" as if they were two different things. What is confusing.

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

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

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

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

Which has the advantage of fewer checks.

To use splice , you will need to keep track of indexes, and I'm not sure if it's worth it. This, of course, would not make reading the code easier. Similarly, I doubt that map would be much more useful than a regular loop.

+9
source share

Use grep if you know the elements you want to keep.

 my @keepers = grep /interesting/, @array; 

If you have an array reference instead, write

 my @keepers = grep /interesting/, @$arrayref; 

Note that this does not modify the array.

The process is similar to map . Given a test that rejects items, write

 my @keepers = map /do not want/ ? () : $_, @array; 

Invert the meaning of the test with

 my @keepers = map /interesting/ ? $_ : (), @array; 
+7
source share

You might also like the extract_by function from List::UtilsBy . It is similar to grep, except that it removes elements from the passed array.

 use List::UtilsBy qw( extract_by ); # some values in @array my @removed = extract_by { m/test/ } @array; # Matching elements will now be removed from @array and appear in @removed. 
+2
source share

All Articles