Needless to say, I rely heavily on perldoc. It's great, but like man pages, I often find them hard to read (man find completely bewilders me -- no humor intended). Today, a coworker was trying to understand overloading and his code was a bit confused. That's fair because when I first tried to understand overload from the docs, I was a bit confused and I eventually resorted to reading Perl modules which used overloading to understand what was going on. So I wrote a tiny example for him:
#!/usr/bin/perl -l
use strict;
use warnings;
{
package Number;
use overload
'+' => \&plus,
'""' => \&value,
fallback => 1;
use Scalar::Util qw(blessed looks_like_number);
use Carp qw(carp croak);
sub new {
my ( $class, $number ) = @_;
unless ( looks_like_number($number) ) {
croak("($number) is not a valid number");
}
return bless { number => $number } => $class;
}
sub value { shift->{number} }
sub plus {
my ( $num1, $num2, $reversed ) = @_;
if ($reversed) {
carp("$num1 and $num2 are reversed");
}
return __PACKAGE__->new(
$num1->value
+
( blessed $num2 ? $num2->value : $num2 )
);
}
}
my $seven = Number->new(7);
my $pi = Number->new(3.14);
# overloading stringification ('""') allows the following to work
print $seven + $pi;
# 'blessed' in &plus allows this to work
print $seven + $pi + 1 + $pi;
# without overloading, the above is:
print $seven->plus($pi)->plus(1)->plus($pi)->value;
# perl's smart enough to reverse these
print 3 + $seven;
While that's perhaps not the best use of overloading, it's clear. Once he saw that, he quickly understood the core concept and the rest of the docs were easy for him to read.
I would love to see more of this in the Perl documentation, right at the beginning of complicated sections.
Thanks to kyle and liverpole for pointing out a small typo (never code in a textarea kids!)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.