Perl is all about "if you treat it as a string, it'll try to behave as a string". If you treat a number as a string, it'll give you the number in decimal form; if you treat an object as a string, it will give you the class, reftype and refaddr (like Object=HASH(0x559ee79cc1e0)).

Some objects are intended to behave like other things, for example Math::BigInt objects are intended to behave like numbers, so when they are stringified you don't want them to show Math::BigInt=HASH(0x559ee79cc1e0), you want them to stringify as a number the same as a normal integer would. That's what this use of overload is doing.

Overloading means you can do this:

% perl -MMath::BigInt -E 'my $x = Math::BigInt->new(2)**100; say $x' 1267650600228229401496703205376 %

There is overloading of the ** operator going on here, and then stringification overload for the say.

Overloading as a general concept is something you want very rarely, but is very useful when you do want it. Once you are aware of it, the main skill is knowing to use it very sparingly - it is usually a really bad idea to have your work code overload the Bank::Account class to make $account += $amount credit the account. But I happen to write a lot of maths code with big integers, and for that context it is incredibly useful.


In reply to Re: What's the point of this 'overload' idiom? by hv
in thread What's the point of this 'overload' idiom? by Cody Fendant

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.