|Just another Perl shrine|
This could have DWIM betterby Aristotle (Chancellor)
|on Mar 01, 2006 at 16:54 UTC||Need Help??|
The recent Chatterbox bug discussion reminded me of a huge pet peeve of mine about Perl (and hugely peevish too, I know): itís such a pain to test string length if you want to accept undefined values without emitting warnings. You have to write something like this:
Itís so redundant and verbose that people will often simply do
and accept that a value of 0 or "0" will produce false negatives with a shrug.
In other words, the easy and obvious way is wrong.
That could have been avoided so simply:
The above test for string length then becomes this:
Since undef silently evaluates to false in boolean context, same as 0, this never throws an uninitialized warning and does the right thing. This version of length is also more useful, since you can tell undefs from empty strings just by looking at the return value, without an extra defined test. Granted, now you have to check the return value for definedness if you want to use it in calculations, but the situation does not actually change, since you need a definedness test in either case Ė either on the passed scalar or on lengthís return value.
Iíve been using this in some scripts for a while, and I love it. I canít think of a single reason why anyone would want to have lengthís current behaviour of returning 0 while throwing a warning on undef scalars, as opposed to returning undef without a complaint. The latter seems more useful and/or less annoying in every case I can come up with.
Of course, itís way too late to do anything about this now. I darenít use it in any complex codebase that relies on a lot of CPAN code either. Maybe something to be dealt with using feature?
Makeshifts last the longest.