The map block can return 0 or more elements for each element in the source list. To omit an element, simply return an empty list () :
my @ids = map { $_->id > 100 ? $_->id : () } @objs;
This assumes that the objects in @objs have an id attribute and associated access. If you want direct hash access, you can also do this:
my @ids = map { $_->{id} > 100 ? $_->{id} : () } @objs;
Or you can just combine map and grep :
my @ids = map { $_->id } grep { $_->id > 100 } @objs;
I'm not sure which one would be more efficient, but if @objs really big, it hardly matters.
If the value you are extracting from the object is expensive to calculate, you can cache the value for the test and return value:
my @vals = map { my $v = $_->expensive_method; $v > 100 ? $v : () } @objs;
cjm
source share