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;
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With