Absolutely right! Using $_ in the sub is bad and "15not" += 0; becomes 15. At the time I was just trying to understand the advice given in Far More Than Everything You've Ever Wanted to Know About... I must confess that I don't get it. Applying the advice given doesn't seem to work in all cases and so of not much use. Using Regex::Common is far and away the best solution that I have found.

New version of the code that still doesn't work.

#!/usr/bin/perl -w use strict; sub i_am_a_number { my $val = shift; no warnings; # += 0 on a string sets off a warning # make sure that zero is counted as a number # ($_ += 0) alone fails on zero. if ($val =~ /^\d+$/ || ($val += 0)) { return 1; } return 0; } ############################################################# # take the sub on a test spin my @list = ( # Zeros 0.00, .00, 0. , 0, -0, 00, # Integers 035, 35, +19, "045 ", " 045", -2, #Floats .15, 5.5, -34.530, # Not numbers " 0 1 ", " 0 0 ", " 24 0 ", " 15hi ", "2isnotanumber", "hi!" ); for (@list) { if (i_am_a_number($_) || i_am_a_number($_)) { print "$_ is a number!\n"; } else { print "$_ is not a number!\n"; } }
()-()
 \"/
  `                                                     

In reply to Re: Re3: How to determine a variable value is a number by ignatz
in thread How to determine a variable value is a number by ciamack

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.