The 2001 Perl Advent Calendar
[about] | [archives] | [contact] | [home]

On the 18th day of Advent my True Language brought to me..
Attribute::Overload

Overloading is great. It allows you to control how your module's objects reacts when being viewed as a string or a number, or how any of the standard operations ('.','+','*', etc) act on your objects. This allows you to do things like implement your own number classes, have your module's object print out sensible stuff if you use them in a print statement, etc.

The traditional way to do overloading is with the "use Overload" directive. This takes a hash of names and values that allows you to specify which method should be used for which operation (including stringification and numification.) This is a very simple approach that suffers from a simple drawback - it's easy to get confused.

Overloading presents a whole new way for a programmer to shoot themselves in the foot. As operations are synthesised from other operations (e.g. if no operation is defined for plus then perl will numify the operator first..then just use normal plus) you can easily get unexpected chains of events. This is confounded by the fact that as a programmer you have to keep going to the top hash, looking up what you said was getting called, scroll back down, meditate on that for a while, scroll back up, look what you think is being called now, etc. It's really tiresome and you soon lose the plot of your evaluation.

Enter Attribute::Overload. This module allows you to declare at each method exactly what overload operator it is connected to. Suddenly everything becomes a lot clearer. You can see right there what will be called. It's not going to stop you shooting yourself in the foot, but it might make it clear exactly where you're pointing the barrel..

  • Overloading in Perl
  • Attribute::Handlers