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

Dear Monks, Why does the following float 0.0 match /^\d+$/ when 0.5 does not? -Jeffrey Friedl

Replies are listed 'Best First'.
Re: Float regex matching
by davido (Cardinal) on Feb 24, 2016 at 16:21 UTC

    Take this example:

    perl -E 'say "match" if 0.0 =~ m/^\d+/'

    This matches. But "." is not included in \d, so why does it match? Because 0.0 is a number that gets implicitly stringified for the purpose of binding to a pattern match. The rules of numeric stringification are to evaluate the numeric value and convert that numeric value to a string representation. Try this, to see it at work:

    perl -E 'my @match = 0.0 =~ m/^(\d+)$/; say "@match";'

    The output will be "0", demonstrating that the value is what gets stringified, not the source code you typed into the keyboard to create the value.

    When you wrap the 0.0 in quotes first, you create a string, "0.0", which is taken exactly as it is, for the purpose being bound to a pattern match.

    On the other hand, the value 0.5 stringifies as "0.5", preserving the decimal point in the process. The decimal doesn't match \d, so the match fails.


    Dave

Re: Float regex matching
by Your Mother (Archbishop) on Feb 24, 2016 at 16:09 UTC

    I expect you can compare these two to see.

    perl -le 'print "OK" if 0.0 =~ /^\d+$/' perl -le 'print "OK" if "0.0" =~ /^\d+$/'
      Looks like Perl resolves 0.0 to 0
        ... Perl resolves 0.0 to 0

        As davido points out below, Perl stringizes 0.0 to '0':

        c:\@Work\Perl\monks>perl -wMstrict -le "my $f = 0.0; my $fs = qq{$f}; print qq{stringization of 0.0: '$fs'}; ;; $f = 0.5; $fs = qq{$f}; print qq{stringization of 0.5: '$fs'}; " stringization of 0.0: '0' stringization of 0.5: '0.5'


        Give a man a fish:  <%-{-{-{-<