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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.