mayaTheCat has asked for the wisdom of the Perl Monks concerning the following question:
Nowadays, I am trying to develop a module which adds the following capability to a number storing scalar: In numeric context the scalar returns the number, and in string context it returns the stringified version of the number - in other words the name of the number.
The typical usage I plan is as follows;
My problem begins with the last two lines of the example above; the increment operator is not overloaded as I expected.use warnings; use strict; use Test::More tests => 6; use Attribute::StringifiableInteger; my $integer : StringifiableInteger = 1; ok($integer == 1); is($integer, 'one'); is(sprintf("%d",$integer), 1); is(sprintf("%s",$integer), 'one'); $integer = 3; $integer += 1; is($integer, 'four'); $integer++; is($integer, 'five');
I wonder whether there is a way to overload the ++ operator or not.use warnings; use strict; package StringifiableInteger; use Carp; use overload '""' => \&_to_string, '0+' => \&_get, '++' => sub { my ($self) = @_; $$self += 1; return 'looks like the return value is not used.'; }, fallback => 1, ; my $regex_integer = qr{ ^ -? \d+ $ }x; sub new { my ($class) = @_; my $integer; bless \$integer, $class; } sub set { my ($self, $value) = @_; croak "invalid integer value ($value)" unless $value =~ $regex_int +eger; $$self = $value; } my @stringified = qw/zero one two three four five six seven eight nine + ten/; sub _to_string { my ($self) = @_; return $stringified[$$self]; } sub _get { my ($self) = @_; return $$self; } package TieStringifiableInteger; sub TIESCALAR { my ($class) = @_; my $integer = StringifiableInteger->new; bless \$integer, $class; } sub STORE { my ($self, $value) = @_; $$self->set($value); } sub FETCH { my ($self) = @_; return $$self; } package AttributeStringifiableInteger; use Attribute::Handlers; sub UNIVERSAL::StringifiableInteger : ATTR(SCALAR) { my ($referent) = @_[2..2]; tie $$referent, 'TieStringifiableInteger'; } 1;
or,use Attribute::StringifiableInteger lang => 'tr';
my $integer : StringifiableInteger('tr');
Thanks in advance,
Oguz
---------------------------------
life is ...
$mutation = sub { $_[0] =~ s/(.)/rand()<0.1?1-$1:$1/ge };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Cannot overload ++ when the object is accessed via Attribute -> Tie -> Class
by Anno (Deacon) on Oct 03, 2007 at 13:19 UTC | |
by mayaTheCat (Scribe) on Oct 03, 2007 at 13:59 UTC |