public
Last active

lvalue accessors

  • Download Gist
lvalue_accessor.pl
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#!/usr/bin/env perl
use strict;
use warnings;
use v5.10;
package Moo::LvalueAccessor;
 
use Scalar::Util qw/weaken/;
use parent 'Exporter';
our @EXPORT = 'AUTOLOAD';
sub TIESCALAR {
my ($class, $attr, $invocant) = @_;
weaken( my $self = $invocant );
my $curry = sub {
return unless $self;
$self->$attr(@_);
};
bless $curry, $class;
}
sub FETCH { $_[0]->() }
sub STORE { $_[0]->($_[1]) }
sub AUTOLOAD :lvalue {
my $self = shift;
my $attr = '_' . (split /::/, our $AUTOLOAD)[-1];
return unless $self->can($attr);
tie my $var, __PACKAGE__, $attr => $self;
$var;
}
package Person;
use Moo;
Moo::LvalueAccessor->import; # use Moo::LvalueAccessor
has '_money' => (
is => 'rw',
default => sub { 0 },
init_arg => 'money',
);
sub payday {
my ($self, $amount) = @_;
$self->money += $amount;
}
package main;
my $person = Person->new;
$person->payday( 200 );
$person->payday( 400 );
say $person->money;

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.