Hi all,
I copy some codes from perltoot and write some lines
to see how AUTOLOAD works.
####test.pl####
#!C:/Perl/bin/perl.exe
use strict;
use warnings;
use Data::Dumper;
use Person;
my $obj=Person->new();
print $obj->name();
print Dumper $obj;
##### Person.pm in the same folder(copy from
perltoot###
package Person;
use Carp;
our $AUTOLOAD; # it's a package global
my %fields = (
name => 'Li',# I define the value
age => 'X', #I define the value
peers => 'O',#I define the value
);
sub new {
my $class = shift;
my $self = {
_permitted => \%fields,
%fields,
};
bless $self, $class;
return $self;
}
sub AUTOLOAD {
my $self = shift;
my $type = ref($self)
or croak "$self is not an
object";
my $name = $AUTOLOAD;
$name =~ s/.*://; # strip
fully-qualified portion
unless (exists
$self->{_permitted}->{$name} ) {
croak "Can't access `$name' field in
class $type";
}
if (@_) {
return $self->{$name} = shift;
} else {
return $self->{$name};
}
}
1;
1) If I call the pre-defined methods there is not
problem with this script.
2) If I call a method undefined by this module ,
such as adding a line code
print $obj->author('Chen');
I will get this wrong message:
Can't access `author' field in class Person
3) If I follow the step 2) and at the mean time
comment out the following line codes
unless (exists $self->{_permitted}->{$name} )
{
croak "Can't access `$name' field in
class $type";
}
I also get what I expect: create a new method on the
fly.
My question: What is the purpose for the condition
statement unless here? It looks like it will prevent
creating a new method on the fly. Any comments?
Thank you very much,
Li
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>