package Math::Base; use strict; use warnings; use overload ( '""' => \&encode, '0+' => \&num, '-' => \&minus, '+' => \&add, '*' => \&mul, '/' => \&div, ); my %hash; my @chars = (0..9,'A'..'Z','a'..'z',map{chr$_}32..47,58..64,91..96); @hash{@chars} = 0..$#chars; sub new { my ($class, $base, $value, $encoded) = @_; my $self = bless [$base, $value], $class; $self->decode if $encoded; $self; } sub rebase { $_[0]->[0] = $_[1] } sub num { shift->[1] } sub minus { my ($self, $other, $swap) = @_; my $result = $self->[1] - $other; $result = -$result if $swap; ref $result ? $result : bless [$self->[0],$result]; } sub add { my ($self, $other, $swap) = @_; my $result = $self->[1] + $other; ref $result ? $result : bless [$self->[0],$result]; } sub mul { my ($self, $other, $swap) = @_; my $result = $self->[1] * $other; ref $result ? $result : bless [$self->[0],$result]; } sub div { my ($self, $other, $swap) = @_; my $result = $swap ? $other / $self->[1] : $self->[1] / $other; int(ref $result ? $result : bless [$self->[0],$result]); } sub encode { my $self = shift; my ($base,$num) = @$self; $num = shift if $_[0]; my ($rem,@ret); while ($num) { push @ret, $chars[($rem = $num % $base)]; $num -= $rem; $num /= $base; } return join '', reverse @ret; } sub decode { my $self = shift; my ($base, $str) = @$self; $str = shift if $_[0]; my $num = 0; $num = $num * $base + $hash{$_} for $str =~ /./g; $self->[1] = $num; } 1; __END__