Well, I can think of quite a few meanings of "is an integer".

  1. Fits in a Perl UV:
    sub isUV { my( $i )= @_; return isIntVal($i) && $i == (0|$i); }
  2. Fits in a Perl IV (no test provided)
  3. Fits in a Perl NV but has no fractional part:
    sub isNVint { my( $i )= @_; return isIntVal($i) && $i == int($i); }
  4. Is the (string) representation of an integer that may not fit into (1), (2), or (3):
    sub isInt { my( $i )= @_; return $i =~ /^-?\d+\z/; }
  5. A scalar that will result in (1), (2), or (3) w/o warning when used in a "numeric context":
    sub isIntVal { my( $i )= @_; return $i =~ /^\s*[-+]?\d+\s*$/; }
    But (update) that doesn't cover "1.2e4", for example, so you can also use (updated):
    sub isIntVal2 { my( $i )= @_; my $warn= 0; { local( $^W )= 1; # my $warn= 0; local( $SIG{__WARN__} )= sub { $warn++ }; $i= 0+$i; } return ! $warn && int($i) == $i; }
  6. A string that will result in literal (1), (2), or (3) w/o warning when used in Perl code (for example, with eval). This one has to allow for _ in the middle, "0x" or "0b" at the start, etc.
And, in particular, (4) has plenty of room for changes based on what you think should be allowed. And my test for (3) doesn't account for numbers that don't accurately fit in an NV.

I really think that the best solution involves making the looks_like_number() C subroutine that Perl itself uses available to scripts.

        - tye (but my friends call me "Tye")

In reply to (tye)Re: Integer detection concept by tye
in thread Integer detection concept by boo_radley

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.