|go ahead... be a heretic|
Unhappy returnsby tlm (Prior)
|on Oct 10, 2005 at 01:33 UTC||Need Help??|
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:
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.
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 context
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.
It is worth noting, however, that, contrary to map, grep evaluates its first argument in scalar context:
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