We don't bite newbies here... much | |
PerlMonks |
Re: What's the point of this 'overload' idiom? (updated)by LanX (Saint) |
on Dec 07, 2022 at 14:08 UTC ( [id://11148650]=note: print w/replies, xml ) | Need Help?? |
> 1. Why would I want this particularly? Operator overloading is a way to adapt operators (not functions) to an object class. For example to define a different algebra° like complex numbers Most operators in Perl are designed for number and string types. Example: If you had $x and $i of a class "ComplexNumber" and wrote $i**$x without overloading, you'd only get the the result from the implicitly numified references. That's hardly useful ... (Update: a more complex example for DateTime objects further down) It can also help adding syntactic sugar to self defined internal DSLs. But it's a complicated matter because you have to keep many side effects in mind when designing such an interface. Like precedence. > 2. what's the specific thing in use in the code I'm seeing, use overload "" => sub {shift->name;}; and why would I want that? Because otherwise the stringification of an object will be the string form of the ref-adress, which isn't helpful.
But overloading "" will make an object return something more meaningful instead in string context. Like it's name from $self->name (sic) HTH!˛ :)
Cheers Rolf °) (abstract) algebra means a set of things and allowed operations mapping set members to other members of the same set. for instance integer arithmetic is an algebra different to real number arithmetics. But division is tricky here, the result of 3/2 (integers) is 1.5 (real number) in Perl. Compare Python where 3/2 is 1, to keep the algebra clean. This different interpretations could be fixed by overloading, tho I doubt that's easily done for native types in Perl. Moreover, in Perl operators rule determine types, while in Python it's the other way round. Best (worst ;) example of mixing those two approaches is JS where 1+1 can occasionally be 11
simply put: Overloading is a way to let types (classes) determine operators. ˛) That's a complicated but interesting subject. I tried my best to come up with good examples, please keep asking if you need more elaboration.
further updatehave a look at the even more complicated overloading in DateTime#Overloading my $new_dt = $dt + $duration_obj; two classes are interacting here DateTime and DateTime::Duration without overloading you'd need to use $dt->add_duration($duration_object) as you can see are overloaded operators a mean to DWIM.
In Section
Seekers of Perl Wisdom
|
|