{
package math;
sub add {
my ($left, $right) = @_; # Look, I am a function
return $left + $right;
}
sub multiply {
my ($class, $left, $right) = @_; # Look, I am a method
my $out = 0;
$out = add($out, $left) for 1..$right; # just humor me here
return $out;
}
}
This class offers both a functional (math::add
) and a class interface (math->multiply
). What if we wanted to make this class have a coherent interface internally, with a strange set of constraints:
- We want to make
math->multiply
call any internalmath::
functions as though they are methods - But we don't want to update those internal functions to know anything about being called as a function-or-method
--- /tmp/1 2015-06-03 18:21:02.700177612 -0400
+++ /tmp/2 2015-06-03 18:20:46.928117006 -0400
@@ -2,7 +2,7 @@
package math;
sub add {
- my ($left, $right) = @_; # Look, I am a function
+ my (undef, $left, $right) = @_; # Look, I am a function
return $left + $right;
}
@@ -10,7 +10,7 @@
sub multiply {
my ($class, $left, $right) = @_; # Look, I am a method
my $out = 0;
- $out = add($out, $left) for 1..$right; # just humor me here
+ $out = $class->add($out, $left) for 1..$right; # just humor me here
return $out;
}
}
How could we go about solving this? What weird bits of Perl might we learn along the way?