in reply to need idiom - compare a number to a string

Since Perl will autostringify as needed, just check to see if $value looks like a number or not. I'd probably do something radically sub-optimal like

$value = lookupString($value) if($value !~ /^\d+$/);

I'm sure one of the monks who has Perl skills above mine (i.e. almost everybody) has a better way, but I think my fragment will avoid too many errors (I'd probably demonstrate paranoia by checking to see if $value is defined before the match)


added in update As chromatic pointed out, the regex I showed only checks for positive integers, with neither signs nor blank padding. Since the OP's posted code includes int($value), I'm concluding values including a decimal point or in exponential notation aren't a concern. The regex should probably look more like this:
$value =~ /^\s*[+-]?\s*\d+\s*$/
which should deal with signed and unsigned integers, but will reject cases where $value includes a radix point or is in exponential notation.

emc

" The most likely way for the world to be destroyed, most experts agree, is by accident. That's where we come in; we're computer professionals. We cause accidents. " — Nathaniel S. Borenstein

Replies are listed 'Best First'.
Re^2: need idiom - compare a number to a string
by chromatic (Archbishop) on Mar 17, 2006 at 23:19 UTC

    Your regex only catches positive integers, which may be okay -- but it's certainly not all valid numbers. Consider negative integers, rationals, and numbers in scientific notation, for exammple.

      It don't think we have to catch those (well, maybe negatives). It sounds like the OP is talking error codes or something similar, which wouldn't be floating point numbers.