davido has asked for the wisdom of the Perl Monks concerning the following question:

I was looking at the code for Scalar::Util, and in specific at the source for the looks_like_number() function. There's something strange in the code that prompts me to ask the question of 'why'.

Here is the source for the looks_like_number() function, pasted from Scalar::Util:

sub looks_like_number { local $_ = shift; # checks from perlfaq4 return $] < 5.009002 unless defined; return 1 if (/^[+-]?\d+$/); # is a +/- integer return 1 if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/); # a C float return 1 if ( $] >= 5.008 and /^(Inf(inity)?|NaN)$/i) or ($] >= 5.006001 and /^Inf$/i ); 0; }

The line I'm questioning is:

return $] < 5.009002 unless defined;

As I understand from reading perlvar, $] contains the version + patchlevel / 1000 of the perl interpreter. The question is why is Scalar::Util's looks_like_number() written to return truth if its parameter is undefined and the version is less than 5.009002? This would mean that the looks_like_number() function will errantly report an undefined value as looking like a number if you're using a sufficiently old version of Perl5. Is this really what is intended? Or am I missing something simple?


Dave

Replies are listed 'Best First'.
Re: Scalar::Util 'looks_like_number()' code's $] comparison
by ysth (Canon) on Dec 15, 2004 at 23:55 UTC
Re: Scalar::Util 'looks_like_number()' code's $] comparison
by eieio (Pilgrim) on Dec 15, 2004 at 23:54 UTC
    I'm not sure, but I would guess that looks_like_number would return true if its parameter was undefined in those earlier version of Perl and this current code exists to maintain compatibility with that original behavior.

    ... this may be the case. Google turned up the following post.