T
Tim McDaniel
So a cow-orker has the result of a database query. It's being
returned as a string: it contains an integer or it's a null string.
(Yes, we're certain.) He wants to use it in a numeric context, but is
getting
Argument "" isn't numeric in numeric eq (==) at FILE line NUMBER.
warnings (as we have "use warnings" on). I had had the impression
that "+ 0" would do the conversion and avoid a warning, but that's not
the case.
Is there an elegant idiom for converting such a string to a number
without producing a warning if it happens to be a null string?
* $t = $t ? 0+$t : 0;
is not what I would call "elegant", especially in this case, where
it's not $t but $alonghashtablename{AVERYLONGHASHINDEXNAME}.
* $t = "0$t" + 0;
isn't so elegant either (though at least it does not convert to
octal, as I first wondered).
* $t ||= 0;
doesn't give you a number per se, but at least the string converts
to a number in numeric contexts without a warning.
* ($t ||= 0) += 0;
Its main virtue is that it converts it to a number and only uses $t
once.
I'm thinking that
{ no warnings 'numeric'; $t += 0; }
is the best choice. It has the great virtue of being abundantly clear
on what they want, as opposed to a person reading having to figure out
some hack that happens to do it without a warning.
I should note that we're using 5.8.8 and NO I have no way whatsoever
of changing that.
returned as a string: it contains an integer or it's a null string.
(Yes, we're certain.) He wants to use it in a numeric context, but is
getting
Argument "" isn't numeric in numeric eq (==) at FILE line NUMBER.
warnings (as we have "use warnings" on). I had had the impression
that "+ 0" would do the conversion and avoid a warning, but that's not
the case.
Is there an elegant idiom for converting such a string to a number
without producing a warning if it happens to be a null string?
* $t = $t ? 0+$t : 0;
is not what I would call "elegant", especially in this case, where
it's not $t but $alonghashtablename{AVERYLONGHASHINDEXNAME}.
* $t = "0$t" + 0;
isn't so elegant either (though at least it does not convert to
octal, as I first wondered).
* $t ||= 0;
doesn't give you a number per se, but at least the string converts
to a number in numeric contexts without a warning.
* ($t ||= 0) += 0;
Its main virtue is that it converts it to a number and only uses $t
once.
I'm thinking that
{ no warnings 'numeric'; $t += 0; }
is the best choice. It has the great virtue of being abundantly clear
on what they want, as opposed to a person reading having to figure out
some hack that happens to do it without a warning.
I should note that we're using 5.8.8 and NO I have no way whatsoever
of changing that.