use strict; use warnings; package Character; use AutoExecute; sub new { my ($class) = @_; return bless({ poisoned => 0, }, $class); } sub poisoned { my ($self) = @_; return auto_execute { my ($poisoned) = @_; $self->{poisoned} = $poisoned if @_; return $self->{poisoned}; }; } package main; my $char = Character->new(); my $poisoned = $char->poisoned; print($poisoned, "\n"); # 0 $poisoned->(1); print($poisoned, "\n"); # 1 $poisoned->(0); print($poisoned, "\n"); # 0
AutoExecute.pm: (Could probably use a better name)
package AutoExecute; BEGIN { our @EXPORT = qw( auto_execute ); *import = \&Exporter::import; } use overload '""' => \&stringify, '&{}' => \&code_ref, ; sub auto_execute(&) { my ($sub) = @_; return bless(\$sub); } sub new { my ($class, $sub) = @_; return bless(\$sub, $class); } sub stringify { my ($self) = @_; my $sub = $$self; return $sub->(); } sub code_ref { my ($self) = @_; my $sub = $$self; return $sub; } 1;
But all of the above would be much faster and just as neat if written as follows:
use strict; use warnings; package Character; sub new { my ($class) = @_; return bless({ poisoned => 0, }, $class); } sub poisoned { my ($self, $poisoned) = @_; $self->{poisoned} = $poisoned if @_ >= 2; return $self->{poisoned}; } package main; my $char = Character->new(); print($char->poisoned, "\n"); # 0 $char->poisoned(1); print($char->poisoned, "\n"); # 1 $char->poisoned(0); print($char->poisoned, "\n"); # 0
In reply to Re: Auto-evaluating anonymous subroutines
by ikegami
in thread Auto-evaluating anonymous subroutines
by dabreegster
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |