Perl: splitting an array into matches and inconsistencies

I know that you can use grepto filter an array based on a logical state. However, I want to get 2 arrays back: 1 for elements that match the condition, and 1 for elements that fail. For example, instead, which requires repeating the list twice:

my @arr = (1,2,3,4,5);
my @evens = grep { $_%2==0 } @arr;
my @odds = grep { $_%2!=0 } @arr;

I would like something like this:

my @arr = (1,2,3,4,5);
my ($evens, $odds) = magic { $_%2==0 } @arr;

Where magicreturns 2 arrayrefs or something like that. Is there such an operator, or do I need to write it myself?

+4
source share
2 answers

Probably the easiest for pushevery value for the correct array in a loopfor

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
+7

List::UtilsBy::extract_by grep :

use List::UtilsBy 'extract_by';
my @arr = (1,2,3,4,5);

my @evens = @arr;
my @odds = extract_by { $_ % 2 } @evens;

print "@evens\n@odds\n";

:

2 4
1 3 5

List::UtilsBy::partition_by:

my %parts = partition_by { $_ % 2 } @arr;
@evens = @{$parts{0}};   # (2,4)
@odds = @{$parts{1}};    # (1,3,5)
+6

Source: https://habr.com/ru/post/1681204/


All Articles