Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^3: Objects with Private Variables

by jbrugger (Parson)
on Jun 08, 2005 at 07:10 UTC ( #464576=note: print w/ replies, xml ) Need Help??


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.


Comment on Re^3: Objects with Private Variables
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://464576]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2014-07-12 17:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (240 votes), past polls