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!)
Cheers,
Ovid
New address of my CGI Course.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Overloading by Example (pieces)
by tye (Sage) on Oct 10, 2007 at 18:32 UTC | |
by Ovid (Cardinal) on Oct 10, 2007 at 18:59 UTC | |
by tye (Sage) on Oct 10, 2007 at 20:15 UTC | |
by eric256 (Parson) on Oct 10, 2007 at 23:32 UTC | |
by tye (Sage) on Oct 11, 2007 at 17:49 UTC | |
Re: Overloading by Example
by syphilis (Archbishop) on Oct 11, 2007 at 01:41 UTC | |
by tye (Sage) on Oct 11, 2007 at 02:44 UTC | |
by Mutant (Priest) on Oct 11, 2007 at 11:29 UTC | |
Re: Overloading by Example
by BrowserUk (Patriarch) on Oct 11, 2007 at 02:18 UTC | |
Re: Overloading by Example
by misc (Friar) on Oct 12, 2007 at 08:16 UTC |