Perl - SUPER - Can't locate object method
I created following 2 files, but when I run sample.pl, its giving me the following error
Can't locate object method "new" via package "sample" at sample.pm line 14.
Any help is appreciated.
Thanks.
package sample;
use strict;
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my %fields = (
Debug => 0,
Error => undef,
@_,
);
my $self = bless $proto->SUPER::new(%fields), $class;
return $self;
}
1;
sample.pl
#!/usr/bin/perl
use strict;
use sample;
my $obj = sample->new();
print "Howdy,开发者_如何学运维 sample\n";
The pseudo-class SUPER
refers to the parent class of the package it appears in (not the parent class of the object that calls it!). You have no parent class. Add a parent class to see it work. Here's an example with a few modifications.
#######################
package ParentSample;
use strict;
use warnings;
sub new {
my( $class, %fields ) = @_;
# some debugging statements so you can see where you are:
print "I'm in ", __PACKAGE__, " for $class\n";
# make the object in only one class
bless \%fields, $class;
}
#######################
package Sample;
use strict;
use warnings;
use base qw(ParentSample);
sub new {
my( $class ) = shift;
# some debugging statements so you can see where you are:
print "I'm in ", __PACKAGE__, " for $class\n";
my %fields = (
Debug => 0,
Error => undef,
);
# let the parent make the object
$class->SUPER::new( %fields );
}
#######################
package main;
use strict;
use warnings;
my $obj = Sample->new( cat => 'Buster' );
print "Howdy, sample\n";
Curiously, this error message got much better in recent versions of perl. Your old perl doesn't put SUPER
in the message:
$ perl5.8.9 sample
Can't locate object method "new" via package "sample" at sample line 14.
$ perl5.10.1 sample
Can't locate object method "new" via package "sample" at sample line 14.
$ perl5.12.1 sample
Can't locate object method "new" via package "sample::SUPER" at sample line 14.
$ perl5.14.1 sample
Can't locate object method "new" via package "sample::SUPER" at sample line 14.
You don't have any use base
in your sample.pm file - it is not inheriting any other package - who do you expect $proto->SUPER
to be?
Instead of using base you can also modity @ISA array and load module yourself:
So
use base "ParentSample";
could be replaced with:
require ParentSample;
@ISA = ("ParentSample");
When modifying @ISA, loading module is important otherwise it won't work. Base load's it for you.
精彩评论