Skip to content

Instantly share code, notes, and snippets.

@schwern
Created July 31, 2012 09:06
Show Gist options
  • Save schwern/3215341 to your computer and use it in GitHub Desktop.
Save schwern/3215341 to your computer and use it in GitHub Desktop.
Operator overload in Perl
#!/usr/bin/env perl
use strict;
use warnings;
use File::Basename;
use lib dirname(__FILE__);
{
package GS_URI;
use strict;
use warnings;
use parent 'URI';
use Scalar::Util qw(blessed);
use overload
'""' => sub { $_[0]->canonical },
'eq' => sub {
my($self, $other) = @_;
print STDERR "overloaded eq\n";
print STDERR "\$self: object - $self->{uri}\n";
if( blessed $other && $other->isa(__PACKAGE__) ) {
print STDERR "\$other: object - $other->{uri}\n";
}
else {
print STDERR "\$other: string - $other\n";
$other = __PACKAGE__->new($other) unless blessed $other;
}
return $self->canonical eq $other->canonical;
},
fallback => 1;
sub new {
my $class = shift;
my $uri = URI->new(@_);
return bless { uri => $uri }, $class;
}
sub canonical {
return $_[0]->{uri}->canonical;
}
}
my $uri1 = GS_URI->new("http://x.com/ blah /");
my $uri2 = "http://x.com/%20blah /";
# operator overloading works even if one side isn't an object
print "Yes\n" if $uri1 eq $uri2;
# order doesn't matter
print "Yes\n" if $uri2 eq $uri1;
# just to show it's actually working
print "No\n" if $uri1 ne "http://blah.com";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment