Or is your question intended to address a more general case?
Of course I would like a solution for the general case. The reason I asked here is that I thought I had missed something obvious, because it seemed such a basic thing to do. At least it is easy in other programming languages I use. I am aware that you can use Perl modules like Math::BigInt, but I hope I can get this done without having to 'include' a huge, slow monster like that. For example, the script I mentioned reads many lines from a file, which may have been generated by another tool. The file may be corrupted or wrong. I just want a general, fast, simple integer validation solution that I can reuse in other scripts I have around.
I had hoped for a ready-made solution, but I'll have to code it myself. So let's recap what I have now:
- Create the largest integer number that the current Perl interpreter supports.
- Convert it to a string.
- Find out how long the string is.
- Check if the "value to parse" has any non-digits with a regular expression like $str =~ m/[^0-9]/; . Or use a ready-made one like Regexp::Common::number .
- Remove all leading zeros.
- If the length is < max length, then it is a fine integer.
- If the length is > max length, then it is too big for us.
- If the length is the same, then a simple lexicographical comparison ( $str1 cmp $str2 ) should work.
Have I missed something?
Before I begin, could we use pack/unpack instead? I am not very familiar with them, but there are several integer types there.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.