I want to generate a bunch of uniformly distributed non-negative integers in a specified range. The guts of my program look like this:

sub main { if (@ARGV < 3) { USAGE: print STDERR ("Usage: $0 low high samples [seed]\n"); exit 1; } my ($lo, $hi, $samples, $seed) = @ARGV; goto USAGE if ($lo > $hi || $samples <= 0); $seed = srand() unless (defined($seed)); srand($seed); my $range = $hi - $lo + 1; while ($samples-- > 0) { printf("%d\n", $lo + int(rand($range))); } } main();

And the code works just fine for run-of-the-mill arguments. But I am a bit of a nut about avoiding unwanted surprises. If somebody supplies a high that is too large to fit in an integer, the program may not do what they intend. Here are some snippets from a debugging session on my PC.

DB<151> say ~0 18446744073709551615 DB<152> say "of course" if (~0 > 18446744073709551614) of course DB<153> say "of course" if (18446744073709551616 > ~0) DB<154> say 18446744073709551616 1.84467440737096e+19

I'd like to catch any case where the arguments are too big to fit in an integer. I can, and probably will, do this using Math::BigInt, but this seems like using a pile driver to crack a peanut. I could, in fact, use Math::BigInt throughout, but far downstream, I want to pack the integers into compact BigEndian numbers, so it's better for me to enforce acceptable values as early as possible.

Is there a simpler way to ensure arguments fit in integers?


In reply to Number too big to fit in integer by jpl

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.