You can subclass any of the standard types, overriding or adding methods and other attributes.
package Radius;
require Tie::Scalar;
@ISA = (Tie::StdScalar);
use overload '*' => \&multiply;
#
# I'm not sure how this goes...
sub multiply {
my $self = shift;
my $other = shift;
return $self->FETCH ** $other;
}
|
class Radius(int):
def __mul__(self, other):
return self ** other
radius = Radius(6378)
# radius acts exactly like an int,
# except when multiplied.
radius / 2.0 # 3189.0
radius * 0.5 # 79.862...
print "Earth's circumference:", int(pi * radius * 2), "km"
|
Perl has no monopoly on evil.