Created
October 3, 2012 01:20
-
-
Save richardplatel/3824359 to your computer and use it in GitHub Desktop.
Perl operator overloading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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