Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl: split array into matches and non-matches

Tags:

arrays

perl

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?

like image 555
ewok Avatar asked Dec 10 '22 10:12

ewok


1 Answers

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;

output

1 3 5
2 4
like image 138
Borodin Avatar answered Dec 12 '22 23:12

Borodin