Lefunque
Lefunque

Reputation: 498

Perl equivalent of Ruby's partition function?

A basic example would be I have an array ['abc','cde','efg'] and want split it into two arrays. One which has the elements containing a c and one with the remaining elements.

In ruby I would just say:

has_c, no_c = arr.partition { |a| a.include?('c') }

Is there a simple perl equivalent?

Upvotes: 1

Views: 190

Answers (2)

choroba
choroba

Reputation: 241768

I tried several things with the ternary operator, this seems to work:

#!/usr/bin/perl
use warnings;
use strict;

my @a = qw[abc cde efg];
my (@has_c, @no_c);
push @{ \(/c/ ? @has_c : @no_c) }, $_ for @a;

print "c: @has_c\nno: @no_c\n";

Update: simplified.

Upvotes: 2

mob
mob

Reputation: 118595

There's the part function in List::MoreUtils:

use List::MoreUtils 'part';
my $listref = [ 'abc', 'cde', 'efg' ];

my ($without_c, $with_c) = part { /c/ } @$listref;

print "with c : @$with_c\n";
print "without: @$without_c\n";

Outputs:

with c : abc cde
without: efg

Upvotes: 9

Related Questions