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

Monks - Any advice on a neat way to numerify any string under strictures without getting a warning?

I know that a string of chars will evaluate to zero in a numeric context, but it does so with a warning, eg.

use strict; use warnings; my $val1 = 'Test'; my $val2 = '5.6'; # $val1 += 0; # How to numerify $val1 without a warning? print "Sum is ", $val1 + $val2, "\n";

The example prints the right answer (5.6) but also issues a warning about the $val1 scalar being non-numeric. I've tried using +=0 and similar to safely numerify it first, but that gets me a warning too.

Is there a trick to doing that? Or it is a case of temporarily turning off warnings?

Replies are listed 'Best First'.
Re: Warning-free numerification of a string
by Fletch (Bishop) on Aug 08, 2007 at 18:32 UTC

    Perhaps use looks_like_number from Scalar::Util to check before you try to numify it? Besides that I think yes, you're going to have to do a { no warnings 'numeric'; ... }.

Re: Warning-free numerification of a string
by clinton (Priest) on Aug 08, 2007 at 18:42 UTC
    Why wouldn't it be a number? Presumably, because it is coming from outside, some uncontrolled source. So you should be checking that the input matches your expectations before processing it. This has the dual benefit of avoiding the warning, and making your program safer.

    Clint

      Sound advice ... now how would I go about "checking the input matches my expectations", those being that it should be a number, or else converted to zero (preferably without turning off warnings to do so). Ah yes, back to the original question then :-)
        Either with Fletch's suggestion of looks_like_number from Scalar::Util, or a regex from Regexp::Common, or if actually, you're just expecting a positive integer, a simple regex like  /^\d*$/
Re: Warning-free numerification of a string
by ikegami (Patriarch) on Aug 08, 2007 at 18:45 UTC
    for ($val1, $val2) { $_--; $_++; }

    works, at least for most values, but

    for ($val1, $val2) { no warnings 'numeric'; $_ += 0; }

    is far less riskier and far more readable/maintainable.

      Thanks! Very sneaky, I like it. Probably a bit too sneaky to be considered maintainable, so I'll run with the latter. At least now I know I'm not missing a neat trick here.
        If $_ is a string that that does not look_like_number(), then don't be fooled into thinking that $_ + 0 will inevitably evaluate to zero:
        $_ = '12*&&#$%'; $_ += 0; print $_, "\n"; # prints 12
        Cheers,
        Rob
        Not sneaky at all, just contain the no-warnings to where you need it and the requirement is crystal-clear:
        { no warnings 'numeric'; $val1 = $val1+0; # force numeric }