Reputation: 498
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
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
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