John M. Dlugosz has asked for the wisdom of the Perl Monks concerning the following question:

The BigInt->new function takes decimal, hex, and binary in the usual Perl literal number syntax. But it doesn't take Octal—it treats a leading zero as nothing special and parses a decimal number.

Even the documentation for autocreating Big constants doesn't mention octal, so presumably those are left as normal scalars. But trying it, I find that

perl -MMath::BigInt=:constant -e"print 077"
and
perl -e"print 077"
produce different results! So that leads to a silent change in the program, which is not good.

The affect of autocreate-constant might be considered a bug at least in the docs, but that's not why I'm writing.

I'm pondering how to parse octal values, changing a program that just reads text from the user and converts to a number using $val = oct($val) if $val =~ /^0/;. Writing $val= new BigInt:: ($val); will handle decimal, binary, hex, but not octal.

My first idea is to detect the leading zero first and convert the octal string into a binary string using only string-based operations, one character at a time. Anybody got a better way?

—John

Replies are listed 'Best First'.
Re: BigInt and octal input
by ysth (Canon) on Feb 04, 2004 at 19:22 UTC
    The string conversion sounds to binary sounds like the best bet. Math::BigInt has historically had a lot of holes and bugs, but the current maintainer has put a lot of work into it, and will respond very quickly to a bug report (hint hint).

    Looks like the failure to take octal is still there in the current version, but do make sure you have an up-to-date Math::BigInt, to avoid already fixed bugs.

Re: BigInt and octal input
by hardburn (Abbot) on Feb 04, 2004 at 17:59 UTC

    You pretty much have to work at the string level, since if you could guarentee the input would fit in a normal integer, you wouldn't be bothering to use a BigInt library.

    ----
    I wanted to explore how Perl's closures can be
    manipulated, and ended up creating an object
    system by accident.
    -- Schemer

    : () { :|:& };:

    Note: All code is untested, unless otherwise stated