[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Omaha.pm] we need a 1 liner
On Nov 14, 2006, at 8:21 PM, Jay Hannah wrote:
Can anyone tell me what the 1 liner for this is before Andy does?
Looks like not. :-)
# Here's the original
my @old = @{$self->{pools}};
my @new;
foreach (@old) {
if (@$_ > 0) {
push @new, $_;
}
}
$self->{pools} = \@new;
# We can easily substitute @old out, and turn the push() into postfix
my @new;
foreach ( @{$self->{pools}} ) {
push @new, $_ if (@$_ > 0);
}
$self->{pools} = \@new;
# What we're really doing is a grep. We're saying "for everything that
# matches a given criteria, stick it in @new". So write it like so
my @new = grep { @$_ > 0 } @{$self->{pools}};
$self->{pools} = \@new;
# Now we can remove the @new entirely with an anonymous array
# constructor.
$self->{pools} = [ grep { @$_ > 0 } @{$self->{pools}} ];
# I think it's clearer this way. What you're saying is:
$self->{pools} = [
# assign an anonymous array that contains
grep
# everything that matches
{ @$_ > 0 }
# the condition that the dereferenced
# "it" is not empty
@{$self->{pools}} ];
# using this list.
Another way to have done the same thing, since you're reading from
and assigning to the same list, would have been to iterate over the
array and delete all the elements such that @{element} == 0, but I
think this one is cleaner to read.
xoxo,
Andy
--
Andy Lester => andy@petdance.com => www.petdance.com => AIM:petdance