http://qs321.pair.com?node_id=464576


in reply to Re: Re: Objects with Private Variables
in thread Objects with Private Variables

Nice, but if you want your class methods to use the class variables, you have to use the getters and setters as well.
I now use your code adjusted like this (also taken the point of misterb101.
package person; use strict; use Carp qw(croak cluk); { my @attributes = (qw/NAME AGE/); sub new { my $type = shift; my $class = ref $type || $type; DEBUG => 1, # Values 0, 1, 2 (0ff, self, include chi +lds) @_ }; my %DataStorage = map { $_ => undef } @attributes; my $self = sub { my ($name, $arg) = @_; #internal setter is able to create variables and getter-se +tter my @caller = caller; if (!exists $DataStorage{$name} && $caller[0] eq $DataSto +rage{CLASSNAME}) { $DataStorage{$name} = $arg; } croak "Method '$name' unknown for class $DataStorage{CLASS +NAME}" unless exists $DataStorage{$name}; $arg and $DataStorage{$name} = $arg; $DataStorage{$name}; }; #### convenience methods are denined here... for my $method ( keys %DataStorage ) { no strict 'refs'; *$method = sub { my $self = shift; $self->( $method, @_ ); }; } bless $self, $class; $DataStorage{DEBUG} = $arg->{DEBUG}; return $self; } } sub salute { my $self = shift; print "Hello, I'm ", $self->NAME, " and I'm ", $self->AGE, "!\n"; # and i'm allowed to set my own object-variable "toes" $self->("TOES",5); print "I've got " . $self->("TOES") . " toes on each foot."; } 1;
"We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.