Created
April 17, 2014 13:42
-
-
Save breezhang/10984401 to your computer and use it in GitHub Desktop.
Perl Singleton Objects
This file contains 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
use feature ":5.14"; | |
use Scalar::Util qw{refaddr }; | |
package BarSingleton; | |
my $this; | |
sub new { | |
if ( !$this ) { | |
$this = bless {}, shift; | |
} | |
return $this; | |
} | |
package foo; | |
use overload q{""} => sub { | |
use Data::Dumper::Concise; | |
return Dumper @_; | |
}, | |
q{+} => sub { | |
my ( $a1, $a2 ) = ( $_[0]->{number}, $_[1]->{number} ); | |
if ( looks_like_number( $a1 . '' ) and looks_like_number( $a2 . '' ) ) { | |
return $a1 + $a2; | |
} | |
return; | |
}; | |
sub AUTOLOAD { | |
$shellcommand = $AUTOLOAD; | |
$shellcommand =~ s/^.*:://; | |
given ($shellcommand) { | |
when (/DESTROY/) { | |
say "[1;31m ............[m"; | |
return; | |
} | |
when (/looks_like_number/) { | |
use Scalar::Util qw/looks_like_number/; | |
looks_like_number(@_); | |
} | |
default { | |
my $e; | |
{ | |
local $@; | |
eval { system("$shellcommand @_") }; | |
$e = $@ if $@; | |
} | |
die if $e; | |
} | |
} | |
} | |
sub new { | |
$self = shift; | |
$class = {}; | |
$number = shift; | |
if ( looks_like_number($number) ) { | |
$class->{number} = $number; | |
} | |
return bless $class, $self; | |
} | |
sub DESTROY { | |
say " [1;34m bye [m"; | |
} | |
package main; | |
printf "[1;32m %d [m \n\n\n", foo->new(1) + foo->new(2); | |
printf "[1;32m %s [m \n", foo->new(4); | |
foo->dir("c:\\"); | |
say "[1;32m Shell Ok [m"; | |
if ( refaddr( BarSingleton->new ) eq refaddr( BarSingleton->new ) ) { | |
say "[1;32m Singleton OK [m"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment