Search code examples
perlattributesselfshift

Error while creating an instance by using $self in a perl script


I try to create an object inside my perl Script. Therefore I have a constructor

new(;@)
{
     my $class = shift;
     my $self = {};
     bless $self, $class;
     $self->_init(@_);
     return $self;
}

And my _init(;@) Function, to initialise the object

my $self = shift;
if( @_ )
{
    my %extra = @_;
    @$self{keys %extra} = values %extra;
}
return;

Am I using this two functions the wrong way? I am starting every other sub with the two lines

my $self = shift;
croak "instance method called for class" unless ref $self;

But I get only syntax / String found where operator expected errors in return for every single time I am using it.

Therefore my Question: Am I using the two functions the right way? I always thought I only need to initialise $self once, like I did, and can point everything I want to it for the rest of the Script.


Solution

  • croak is not loaded by default. You must use Carp in the package to be able to use it (see Carp).

    BTW, prototypes are ignored with method calls. Don't use them. Don't use them for functions, either.

    You might use something like Class::Declare::Attributes to save some typing:

    sub new :class {
        ...
    }