On 09/22/2006 08:30 AM, chen li wrote:
Hi all,I copy some codes from perltoot and write some linesto 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 timecomment out the following line codesunless (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?
Yes, it will prevent creation of a new method on the fly if the method name is not in the permitted fields list.
Try this:
$obj->name('Roger');
print $obj->name(), "\n";
Although you didn't create a static "name" method, autoload "created"
one on the fly[0]. It did this because "name" is in the list of
permitted fields.
Thank you very much, Li
You're welcome. --0: This is a simplification. AUTOLOAD doesn't create new methods unless you tell it to; here, AUTOLOAD just performed the desired operations.
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>
