Operator overloading - redefining addition and other Perl tricks
Archive - Originally posted on "The Horse's Mouth" - 2009-09-27 00:45:15 - Graham Ellis
What does addition actually mean? It means different things depending on what you're adding together, and in Perl you can redefine additions - and other operators - on objects of types which you define. This is known as operator overloading, and there's a complete code example here.
So ... how do you do it? Within your class, call up the overload program to redirect the operator that you're overloading to a sub of your choice. And provide that sub - with two parameters passed in through @_ for the two objects being added. Within the sub you should check that you really do have objects (my example is kept simple and does not have this check) and if you do, construct a new object that's a combination of the inputs.
I've chosen - for my example - to stack boxes which have an "x" and a "y" dimension; the new combined box when you add two of them together has an "x" which is the sum of the two "x"es, and a "y" which is the greater of the two "y"s.
Operators can be overloaded in Python too (example) and in C++ (example), but not in PHP, which is a loosely typed language.
Illustation ... I might look for a clever title like "adding pieces to a jigsaw puzzle" ... but actually these are delegates on a private Perl course at our training centre and hotel, relaxing during the evening in the old fashioned way by doing a jigsaw. Our courses provide not only the lectures and practical sessions, but also a chance to get to know your colleagues better, and to exchange ideas with other delegates learning the same subject.