in reply to Using tie to return value of anonymous sub
Then, you would use it as so:package Dabreegster::Attribute::Maker; use strict; use warnings; # if $] >= 5.6.0; sub import { shift; my $pkg = caller; foreach my $attr ( @_ ) { # We're doing symbol-table manipulation here, so # the prohibition against soft references needs to # be relaxed, but only within this context. no strict 'refs'; my $getter = "${pkg}::${attr}"; my $setter = "${pkg}::set_${attr}"; # We will only define the function if the function # hasn't already been defined. *{ $getter } = sub { my $self = shift; if ( (Scalar::Util::reftype( $self->{$attr} ) || '') eq 'C +ODE' ) { return $self->{$attr}->( @_ ); } else { return $self->{$attr}; } } unless defined \&{ $getter }; *{ $setter } = sub { my $self = shift; if ( @_ ) { $self->{$attr} = shift; } return $self; } unless defined \&{ $setter }; } return; } 1; __END__
This code plays nicely with inheritance so long as all your object representations are hashrefs. But, given your original design, I don't think that's going to be a problem.package Character::Player; use Dabreegster::Attribute::Maker qw( str dex con int wis cha ); # Now, you have access to the following functions: # str(), set_str(), dex(), set_dex(), etc.
|
|---|