Created
April 7, 2014 22:33
-
-
Save ian-kent/10069404 to your computer and use it in GitHub Desktop.
Doing weird things with objects in Perl
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/env perl | |
package Foo { | |
use Mojo::Base '-base'; | |
sub new { | |
my $class = shift; | |
my $store = {}; | |
bless sub { | |
my $opt = shift; | |
$store->{base} //= $class->SUPER::new; | |
return $opt && exists $store->{$opt} ? $store->{$opt} : $store; | |
}, $class; | |
} | |
sub bar { | |
my ($self) = shift; | |
return $self; | |
} | |
} | |
my $f = Foo->new; | |
print '$f = ' . $f . "\n"; | |
print '$f->() = ' . $f->() . "\n"; | |
print '$f->("base") = ' . $f->("base") . "\n"; | |
print '$f->bar = ' . $f->bar . "\n"; | |
print '$f->("base")->bar = ' . $f->("base")->bar . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment