in reply to Re: How does Math::GMP overload the assignment operator ? (more guessing)
in thread How does Math::GMP overload the assignment operator ?

"0+" => sub { $_[0] >= 0 ? uintify($_[0]) : intify($_[0]) },

I don't think it's related to my particular problem, but it's an interesting case.
Which operator is being overloaded here ? Is it overloading 'int' ?
I actually wonder if that's a useful feature, but I won't rush to an assessment on that until I've found out a bit more about it.

Cheers,
Rob
  • Comment on Re^2: How does Math::GMP overload the assignment operator ? (more guessing)
  • Download Code

Replies are listed 'Best First'.
Re^3: How does Math::GMP overload the assignment operator ? (more guessing)
by jcb (Parson) on Nov 09, 2020 at 03:15 UTC

    That is overloading numeric conversion.

    That sub will be called whenever an object is used in a context that expects a number.

      That sub will be called whenever an object is used in a context that expects a number.

      The only way I can find of having that sub called is by doing int($obj).
      Do you have an example of another way ?

      On Windows (where sizeof(long) is 4):
      C:\>perl -MMath::GMP -le "print int(Math::GMP->new(311) ** 100);" 385227681
      Math::GMPz achieves the same result with:
      C:\>perl -MMath::GMPz=":mpz" -le "print Rmpz_get_ui(Math::GMPz->new(31 +1) ** 100);" 385227681 alternatively: C:\>perl -MMath::GMPz -le "$x = (Math::GMPz->new(311) ** 100) & 429496 +7295; print $x;" 385227681
      though, in this very last example, $x is a Math::GMPz object, not an IV.

      Cheers,
      Rob

        If there were arithmetic operators that were not overloaded, Perl would invoke numeric conversion before using the builtin arithmetic operations, but I expect Math::GMP to overload all of them, so int may be the only built-in that actually invokes the numeric conversion.

        I expect (but am not certain) that the '0+' overload is also invoked if an XSUB attempts to convert an object to an IV or UV. This is probably (but I have not traced the code) also how builtin arithmetic operations (which are not used on Math::GMP objects) would end up invoking it.