Last active
December 6, 2017 09:29
-
-
Save akanehara/984f612c38c410b27ebd8cfb2ee8f187 to your computer and use it in GitHub Desktop.
Bunchオブジェクト (Perl)
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
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
package Bunch { | |
sub new { | |
my $class = shift; | |
my $self = {@_}; | |
bless $self, $class; | |
} | |
sub AUTOLOAD { | |
our $AUTOLOAD; | |
if (my ($name) = ($AUTOLOAD =~ /.*::(.*)/)) { | |
no strict 'refs'; | |
*{$AUTOLOAD} = sub { # 代替処理 | |
my ($self, $value) = @_; | |
my $r = \$self->{$name}; | |
$$r = $value if (defined $value); # 更新 | |
$$r; | |
}; | |
use strict 'refs'; | |
goto &{$AUTOLOAD}; # 現行のスタックフレームを破棄して代替処理を呼び出す | |
} | |
} | |
sub DESTROY {} # スコープアウトで代替処理が動作しないように | |
1; | |
}; | |
my $bunch = Bunch->new(foo=>99); | |
$bunch->beast(666); | |
print "foo: ".$bunch->foo."\n"; | |
print "beast ".$bunch->beast."\n"; | |
print "lucky ".$bunch->lucky(777)."\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment