Please Support The Fight Against EU Software Patents
Visit The Hitchhiker's Guide To The Galaxy -- earth version

IsNumber

A beautiful piece of perl hackery that came to me one day. The standard way of telling what's a number and what isn't is to use regular expressions. Why bother, when perl knows? And will handily give a warning if you try and use a non-number as a number. Which suggests the following routine...

# Broken. Do not use!

sub IsNumber
{
    eval
    {
        local $SIG{__WARN__} = sub { die };

        scalar ($_[0] == $_[0]);
    };

    !$@;
}

I've made it as hard for newcomers to the language to understand as I can, in the long-standing tradition of perl code.

As you might expect, it's slower than regular expressions when the value isn't a number, because of the exception handling. If it is a number, however, then this is potentially faster. (Particularly if it has lots of digits).

So this code might actually be useful. Scary.

IsNumber v2

Someone very helpfully emailed to point out that the above code is broken. Perl might warn when you try and use a string as a number... but only the first time. After that the numerical representation is cached. So the above function works the first time you try it, provided you haven't already evaluated in a numerical context, and fails the next time. A very nasty bug indeed.

However, in the spirit of perl hackery, I believe I have a solution. By forcing the variable to always evaluate as a string, the warning remains:

# Hopefully less broken.

sub IsNumber
{
     eval
     {
         local $SIG{__WARN__} = sub { die };
         scalar ($_[0]."" == $_[0]);
     };

     !$@;
}

Sadly the alleged speed improvement is probably gone, and I wouldn't bet on there being no remaining subtle bugs.

That's perl for you, I suppose...