mascip has asked for the wisdom of the Perl Monks concerning the following question:
* Edit : Solved. It was because of namespace::autoclean => i'll use namespace::sweep instead.
None of the operators overloading work in this simple example. What did i do wrong? Probably a simple stupid mistake...
Here is the code (Percent class, followed by very simple script), and the printed output is in comments.
#!/usr/bin/perl use 5.012003; # Perl version requirement #=========================================================== # Percentage CLASS (script below) #=========================================================== package Percentage; use Any::Moose; use namespace::autoclean; has 'int' => ( is => 'ro', isa => 'Int', ); around BUILDARGS => sub { my $orig = shift; my $class = shift; print "build\n"; return $class->$orig(int => @_); }; use overload q{""} => \&to_string, '0+' => \&to_num, '+' => \&add; sub to_string { my $self = shift; print "to_string()\n"; return $self->int(); } sub to_num { my $self = shift; print "to_num()\n"; return $self->int(); } sub add { my ($left, $right) = @_; print "add()\n"; my $result = new Percentage( $left->int() + $right->int() ); return $result; } __PACKAGE__->meta->make_immutable; 1; #=========================================================== # SCRIPT #=========================================================== package Example::Script; use 5.012003; # Perl version requirement use strict; use warnings; # printed in output : my $a = new Percentage(2); # build print "$a\n"; # Percentage=Hash(0x11cfe8c) my $a_num = $a->int(); # my $a_str = "$a"; # print "$a_str, $a_num\n"; # Percentage=Hash(0x11cfe8c), 2 my $b = new Percentage(3); # build my $c = $b + $a; # print "$b, $c\n"; # Percentage=Hash(0x116912c), 3693356
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Help! Overloading operators doesn't work
by Corion (Patriarch) on Sep 01, 2012 at 11:30 UTC | |
by mascip (Pilgrim) on Sep 01, 2012 at 11:58 UTC | |
Re: Help! Overloading operators doesn't work
by philiprbrenan (Monk) on Sep 01, 2012 at 11:37 UTC | |
by mascip (Pilgrim) on Sep 01, 2012 at 11:46 UTC |
Back to
Seekers of Perl Wisdom