in reply to What's the point of this 'overload' idiom?
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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: What's the point of this 'overload' idiom?
by stevieb (Canon) on Dec 07, 2022 at 05:13 UTC | |
by LanX (Saint) on Dec 07, 2022 at 14:25 UTC | |
by eyepopslikeamosquito (Archbishop) on Dec 08, 2022 at 12:40 UTC | |
by eyepopslikeamosquito (Archbishop) on Dec 08, 2022 at 12:40 UTC | |
Re^2: What's the point of this 'overload' idiom?
by Cody Fendant (Hermit) on Dec 07, 2022 at 07:01 UTC | |
by stevieb (Canon) on Dec 07, 2022 at 07:33 UTC |