Chapter 34. Overloading

Hildo Biersma

This article describes Perl’s operator overloading, a feature that allows user-defined types to act in the same way as built-in types such as strings and numbers. It’s one of the main strengths of C++, and one of the most glaring omissions in Java.

If you’ve been debugging your program with Data::Dumper and suffering output that looks like MyType=HASH(0xDEADBEEF), or if you’re still invoking compare ($first, $second) when you’d prefer to say $first == $second or $first eq $second, operator overloading can help.

This article starts by creating a simple user-defined type and then extends it to act as much like a built-in type as possible. After I’m done, you’ll be able to decide how and when operator overloading should be used, and how to implement these features for your own types.

Defining Your Own Types

Perl 5 has always allowed you to add your own data types to the language via object-oriented programming. In this article, I’ll define my own Date type that stores date stamps with a resolution of one day. It will support easy formatting in textual, European, and U.S. formats, provide easy comparison between dates, and allow simple arithmetic on dates.

Start by defining a simple Date class, in its own module. The class contains a new method, shown below:

 # Constructor: get day, month, year, return object sub new { my ($class, %args) = @_; # Argument checking $args{'month'} -= 1; # should be done here $args{'year'} -= 1900; # and here my $ctime = timelocal(0, ...

Get Computer Science & Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.