Consider this script:
use strict;
use warnings;
use Devel::Peek;
use bigint;
my $x = "900000000000000000000000000000000000009";
my $y = 900000000000000000000000000000000000009;
#Dump($x);
# Shows that $x is a simple perl scalar
#Dump($y);
# Shows that $y is already a Math::BigInt object.
my $m = $x - 2;
my $n = $x - "2";
if($m == $n) {print "ok\n"}
else {print "$m\n$n\n"}
# Outputs:
# 900000000000000000000000000000000000007
# 9e+038
Question 1:
If $y is automatically a Math::BigInt object, then why not the same for $x ?
Answer:
Because then there would be no way to assign a string of numbers as simply "a string of numbers" - such a string would automatically be converted into a Math::BigInt object (and there's nothing to suggest you want that to happen).
That has relevance to the code you posted in your original script because when you read from STDIN, you're reading a *string*.
Question 2:
Why should
$x - 2 and
$x - "2" return different values ?
Answer:
... I don't have a satisfactory explanation of that, and you might like to query it (via a
perlbug report) with p5p.
UPDATE: OP did file a bug report with p5p, and Lucas Mai pointed out that with
$x - 2 the bareword 2 gets automatically turned into a Math::BigInt object and then gets subtracted from the string $x (thanks to Math::BigInt overloading), returning a Math::BigInt object.
But with
$x - "2" there's nothing happening that will create any Math::BigInt object, so it's just "string - string" which, of course, produces different results. It's obvious when you look at it the right way ... but the effect still seems odd to me.
/UPDATE
That's also of relevance to the code you posted because your
$a - $b is "string - string", just the same as my
$x - "2" (which also fails to upgrade either argument to a Math::BigInt object).
It's issues like these that strongly deter me from using bigint.
IMO, if you're wanting a pure-perl solution for your bigint handling then you're better off using Math::BigInt explicitly.
And if you want efficient bignum handling you should just forget about *pure-perl* solutions altogether and look at using modules such as Math::GMP, Math::GMPz (plug), Math::GMPq (plug), Math::MPFR (plug) and Math::Pari.
Cheers,
Rob