Perl相当于Ruby的分区函数?

时间:2013-03-08 16:35:26

标签: ruby arrays perl

一个基本的例子是我有一个数组['abc','cde','efg'],并希望将它分成两个数组。一个元素包含c,另一个元素包含其余元素。

在红宝石中,我只想说:

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

是否有一个简单的perl等价物?

2 个答案:

答案 0 :(得分:9)

part中有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";

输出:

with c : abc cde
without: efg

答案 1 :(得分:2)

我用三元运算符尝试了几件事,这似乎有效:

#!/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";

更新简化。