Comme les autres réponses suggèrent, grep
est généralement tout ce que vous avez besoin.
Cependant, il est possible avec perl prototypes pour coder une fonction qui, comme Array#reject!
de rubis:
- accepte un bloc
- peut modifier son tableau d'arguments en place
L'utilisation est:
@foo = (2, 3, 6, 7); # Void context - modify @foo in place
reject { $_ > 3 } @foo; # @foo is now (2, 3)
@foo = (2, 3, 6, 7); # Scalar context - modify @foo in place
$n = reject { $_ > 3 } @foo; # @foo is now (2, 3), $n is length of modified @foo
@foo = (2, 3, 6, 7); # Array context - return a modified copy of @foo
@cpy = reject { $_ > 3 } @foo; # @cpy is (2, 3), @foo is (2, 3, 6, 7)
Mise en œuvre:
sub reject(&\@) {
my ($block, $ary) = @_;
# Return a copy in an array context
return grep {! $block->() } @$ary if wantarray;
# Otherwise modify in place. Similar to, but not
# quite, how rb_ary_reject_bang() does it.
my $i = 0;
for (@$ary) {
next if $block->();
($ary->[$i], $_) = ($_, $ary->[$i]); # swap idiom to avoid copying
$i++; # possibly huge scalar
}
$#$ary = $i - 1; # Shorten the input array
# We differ from Array#reject! in that we return the number of
# elements in the modified array, rather than an undef value if
# no rejections were made
return scalar(@$ary) if defined(wantarray);
}
Woah, impressionnant. Je pensais que je posais la question Perl complète d'un débutant là, mais votre réponse est votre troisième plus mise à jour. : o –
@ Shtééf: les questions du débutant sont souvent des questions utiles. –
@knittl Votre solution pourrait-elle être étendue pour remplacer <= avec une expression régulière? – Bnjmn