Main Content

What do I mean when I add things in Perl?

Archive - Originally posted on "The Horse's Mouth" - 2011-08-02 22:56:59 - Graham Ellis

Some things have a natural concept of addition. And of multiplication.

You can add numbers - 5 + 7 gives 12. You can add strings of text - "Hello " + "World" = "Hello World". You can add day trippers to a train and get a busier train (and add too many and you'll get an overcrowded unhappy train, add too few and you'll get an unjustified service). But you can't sensibly do certain addion operations. You can't add the colour purple to a DNS enquiry on port 53; it's a meaningless concept.

Perl's "+" operator works by default on numeric values - be they integers or floats. And you can redefine it on any of your own objects ("packages") if you wish, using the overload pragma. There's an example from last week's Perl for larger projects course - source code [here].

In the example (the source code is commented), I have shown an example of how to overload the "+" operator on an object of type box. Adding boxes together stacks them, so you get the greater of the two width and depth values, and the sum of the two heights, in a new box. But you have far more flexibiity than that - if I had wished, I could have returned an object of a different type, or added something other than a box to a box. Indeed, I've shown a multiplication example where I use a stack of identical boxes, and the second parameter in this case was a number.

When are two boxes "equal"? The most obvious answer is when all their attributes are the same, but it could be that you want something else. By overloading ==, I have redefined equality on boxes, considering them to be equal if they have the same volume.

And what do I get when I print out a variable that contains a box object? Without any instruction in the class, I'll get the fact that it's a box, the memory address at which it is held, and a note about the internal variable type that holds all the data about it. Overload the "" operator though, and you can change fromn the default to something which usefully described the object. Again, there's a commented example in the program that illustrates this article.

There's a further article [here], and a shorter source example showing just addition [here].