Skip to content

Instantly share code, notes, and snippets.

@richardplatel
Created October 3, 2012 01:20
Show Gist options
  • Save richardplatel/3824359 to your computer and use it in GitHub Desktop.
Save richardplatel/3824359 to your computer and use it in GitHub Desktop.
Perl operator overloading
#!/usr/bin/perl
use strict;
use warnings;
package MyFoo;
use Data::Dumper;
use overload
'""' => "stringify",
'<=>' => "compare",
'cmp' => "compare",
;
sub new {
my $self = {
ord => int(rand(100))
};
return bless $self;
}
sub stringify($)
{
my $self = shift;
return "Fooval" . $self->{ord};
}
sub compare($$)
{
my ($a, $b) = @_;
return $a->{ord} <=> $b->{ord};
}
if ($0 eq __FILE__)
{
my @foos;
push @foos, new MyFoo() for (1 .. 10);
print "$_\n" for (@foos);
print "\n\n";
print "$_\n" for (sort @foos);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment