Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Bunchオブジェクト (Perl)
#!/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