pg has asked for the wisdom of the Perl Monks concerning the following question:
I am porting a Java class that calculates RealChallenge for RTSP. That package uses both Java operator >> and >>>. When I port it to Perl, I tried overloading. But I came to some questions.
I can mimic >> and >>> easily with use integer:
use strict; use warnings; print unsigned_shift(-4, 2), "\n"; print signed_shift(-4, 2), "\n"; print unsigned_shift(-4, 2), "\n"; print signed_shift(-4, 2), "\n"; print unsigned_shift(-4, 2), "\n"; print signed_shift(-4, 2), "\n"; sub signed_shift { use integer; return $_[0] >> $_[1]; } sub unsigned_shift { return $_[0] >> $_[1]; }
But the following does not work, but gives no warning/error. I guess you cannot overload core function, or did I do soemthing wrong?
use Data::Dumper; use strict; use warnings; use overload '>>' => \&singed_shift; #use overload 'main::>>' => \&singed_shift; #print Dumper(\%OVERLOAD); print -4 >> 2; sub signed_shift { use integer; return $_[0] >> $_[1]; }
I can put this in a package which will work:
package Number; use strict; use warnings; use overload '>>' => \&signed_shift; sub new { my $self; $self->{"number"} = $_[1]; bless $self; return $self; } sub signed_shift { my ($self, $n) = @_; use integer; return ($self->{"number"} >> $n); } 1; use Data::Dumper; use Number; use strict; use warnings; my $n = new Number(-4); print $n >> 2;
The other question is whether I can "overload" an operator that does not exist. for example whether I can '>>>' => \&blah. When I tried it, it didn't work (didn't like >>>). I don't think I can do that.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: overloading core function and non-existing operator
by Zaxo (Archbishop) on Aug 07, 2005 at 22:34 UTC | |
by QM (Parson) on Aug 08, 2005 at 19:21 UTC | |
|
Re: overloading core function and non-existing operator
by tlm (Prior) on Aug 07, 2005 at 22:38 UTC | |
by pg (Canon) on Aug 07, 2005 at 22:53 UTC | |
by tye (Sage) on Aug 08, 2005 at 06:04 UTC | |
by tinita (Parson) on Aug 08, 2005 at 09:54 UTC |