#!/usr/bin/perl use strict; use warnings; use Data::Dumper; package HexNumber; use Moose; use overload '+' => \&add, '""' => \&to_s; has '_value' => ( is => 'rw' ); sub set { my $self = shift; my $val = shift; return unless $val =~ /^[\da-fA-F]+$/; $self->_value(hex($val)); } sub add { my $self = shift; my $other = shift; return (blessed $other) ? HexNumber->new(_value => $other->_value + $self->_value) : HexNumber->new(_value => $other + $self->_value) ; } sub to_s { my $self = shift; return sprintf '%x', $self->_value; } package main; sub to ($) { shift } # just syntactic sugar my $foo = HexNumber->new(_value => '44800'); # only dec-values directly my $bar = HexNumber->new(); set $bar to 'fe'; # the same as $bar->set('fe'); my $buz = $foo + $bar; print $buz, "\n" x 2; print Dumper \$buz;