I know you can use grep
to filter an array based on a boolean condition. However, I want to get 2 arrays back: 1 for elements that match the condition and 1 for elements that fail. For example, instead of this, which requires iterating over the list twice:
my @arr = (1,2,3,4,5);
my @evens = grep { $_%2==0 } @arr;
my @odds = grep { $_%2!=0 } @arr;
I'd like something like this:
my @arr = (1,2,3,4,5);
my ($evens, $odds) = magic { $_%2==0 } @arr;
Where magic
returns 2 arrayrefs or something. Does such an operator exist, or do I need to write it myself?
It's probably most succinct to simply push
each value to the correct array in a for
loop
use strict;
use warnings 'all';
my @arr = 1 .. 5;
my ( $odds, $evens );
push @{ $_ % 2 ? $odds : $evens }, $_ for @arr;
print "@$_\n" for $odds, $evens;
1 3 5
2 4
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