Dear monks,
I wrote this bug last week. It's not a particularly nasty bug, but it looks so innocent I thought I'd share, particularly for the benefit of brothers and sisters who are getting the hang or using map.
In essence, the code was meant to produce an array of numbers from an array of objects, like this:
But some of the elements in @$arr could be undefined, and of those that were defined, some could have the string 'NA' or undef returned by the value method. I wanted all these cases to show up as undef in the LHS, so I wrote something like this:my @row = map $_->value, @$arr;
Spot the bug? It's in the second return statement of val. Without an argument, it causes val to return undef in scalar context, but return the empty list in list context. As it happens, map evaluates its first argument in list context. Bottom line: even though, in every iteration, the size of @$arr was the same, the size of @row would sometimes be smaller.for my $arr ( @results ) { ... my @row = map val( $_ ), @$arr; ... } sub val { my $o = shift; if ( defined $o ) { my $v = $o->value; return $v if defined $v and $v ne 'NA'; } return; }
Here's a simple illustration of the same thing:
Note that the output has 4 elements, while the input had 5. If one wants those undefs in the output from map, one either has to force the scalar contextsub foo { if ( $_[ 0 ] % 3 } { return $_[ 0 ]; # argument divisible by 3 } return; } print join( ':', map foo( $_ ), 1..5 ), "\n"; __END__ 1:2:4:5
or change the last statement in foo to an explicit return undef; . I'd pick the former approach for flexibility, the latter one for clarity.print join( ':', map scalar foo( $_ ), 1..5 ), "\n"; __END__ 1:2::4:5
It is worth noting, however, that, contrary to map, grep evaluates its first argument in scalar context:
print join( ' ', grep sub { wantarray ? 0 : 1 }, 1..3 ), "\n"; __END__ 1 2 3
Update: Twice I referred to "second argument" (of map/grep) when I meant "first argument". I'm still scratching my head over the origins of this braino, but thanks to itub for pointing it out.
the lowliest monk
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Unhappy returns
by Aristotle (Chancellor) on Oct 10, 2005 at 01:56 UTC | |
Re: Unhappy returns
by ysth (Canon) on Oct 10, 2005 at 04:34 UTC | |
by thor (Priest) on Oct 10, 2005 at 11:59 UTC | |
by Perl Mouse (Chaplain) on Oct 10, 2005 at 12:53 UTC | |
by Aristotle (Chancellor) on Oct 10, 2005 at 14:33 UTC | |
by ysth (Canon) on Oct 10, 2005 at 15:23 UTC | |
| |
Re: Unhappy returns
by Errto (Vicar) on Oct 10, 2005 at 04:01 UTC | |
by Perl Mouse (Chaplain) on Oct 10, 2005 at 09:56 UTC | |
by Aristotle (Chancellor) on Oct 10, 2005 at 10:53 UTC | |
by Keystroke (Scribe) on Oct 10, 2005 at 15:09 UTC | |
by dragonchild (Archbishop) on Oct 10, 2005 at 17:32 UTC | |
by Perl Mouse (Chaplain) on Oct 10, 2005 at 16:00 UTC | |
Re: Unhappy returns
by dragonchild (Archbishop) on Oct 10, 2005 at 17:26 UTC |
Back to
Meditations