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.
In reply to overloading core function and non-existing operator by pg
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |