in reply to Re^3: Reliably parsing an integer
in thread Reliably parsing an integer
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.