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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.