Can someone tell me why the main does not find the methods generated by Class::Accessor in this very small and trivial example ?
These few lines of code fail with
perl codesnippets/accessor.pl
Can't locate object method "color" via package "Critter" at
codesnippets/accessor.pl line 6.
see the code:
#!/opt/local/bin/perl
# The whole Class::Accessor thing does not work !!
my $a = Critter->new;
$a->color("blue");
$a->display;
exit 0;
package Critter;
use base qw(Class::Accessor );
Critter->mk_accessors ("color" );
sub display {
my $self = shift;
print "i am a $self->color " . ref($self) . ", whatever this word means\n";
}
FM is giving you good advice.
mk_accessorsneeds to run before the other code. Also, normally you’d putCritterin a separate file anduse Critterto load the module.This works because
usehas compile time effects. Doinguse Critter;is the same as doingBEGIN { require Critter; Critter->import; }This guarantees that your module’s initialization code will run before the rest of the code even compiles.It is acceptable to put multiple packages in one file. Often, I will prototype related objects in one file, since it keeps everything handy while I am prototyping. It’s also pretty easy to split the file up into separate bits when the time comes.
Because of this, I find that the best way to keep multiple packages in one file, and work with them as if I were using them, is to put the package definitions in
BEGINblocks that end in a true value. Using my approach, your example would be written: