Perl class :: Access error, trivial example - why?

Can someone tell me why the main one does not find the methods generated by Class :: Accessor in this very small and trivial example?

These few lines of code do not work with

perl codesnippets/accessor.pl
Can't locate object method "color" via package "Critter" at
codesnippets/accessor.pl line 6.

see 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";
    }
+5
source share
3 answers

FM gives you good advice. mk_accessorsneed to run before other code. In addition, you usually add Critterto a separate file and use Critterto load the module.

, use . use Critter; BEGIN { require Critter; Critter->import; } , , .

. , , . , .

- , , , - BEGIN , . , :

#!/opt/local/bin/perl

my $a = Critter->new;
$a->color("blue");
$a->display;

BEGIN {
    package Critter;
    use base qw(Class::Accessor );

    use strict;
    use warnings;

    Critter->mk_accessors ("color" );

    sub display {
         my $self = shift;

         # Your print was incorrect - one way:
         printf "i am a %s %s whatever this word means\n", $self->color, ref $self;

         # another:
         print "i am a ", $self->color, ref $self, "whatever this word means\n";

    }

    1;
}
+3

. , color , mk_accessors , . :

package Critter;
use base qw(Class::Accessor);
Critter->mk_accessors("color");

sub display {
    my $self  = shift;
    print $self->color, ' ', ref($self), "\n";
}

package main;
my $c = Critter->new;
$c->color("blue");
$c->display;

Critter (Critter.pm), mk_accessor , script use Critter - script Critter Varmint.

+8

I just wanted to give you a better solution - feel free to lower it to oblivion if the solution is not welcome, but C :: A is a really bad idea for this day and age, use Moose :

package Critter;
use Moose;

has 'color' => ( isa => 'Str', is => 'rw' ); # Notice, this is typed

sub display {
    my $self = shift;
    printf (
        "i am a %s %s whatever this word means\n"
        , $self->color
        , $self->meta->name
    );
}

package main;
use strict;
use warnings;

my $c = Critter->new;  # or my $c = Critter->new({ color => blue });
$c->color("blue");
$c->display;
+2
source

All Articles