Skip to content

Instantly share code, notes, and snippets.

@akanehara
Last active December 6, 2017 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akanehara/984f612c38c410b27ebd8cfb2ee8f187 to your computer and use it in GitHub Desktop.
Save akanehara/984f612c38c410b27ebd8cfb2ee8f187 to your computer and use it in GitHub Desktop.
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