tags:

views:

71

answers:

2

I have these two modules :

package G1;

sub new {
    my $class = shift;
    my $self = {
     one => 1,
     two => 2,
     three => 3
    };
    bless $self,$class;
    return $self;
}

sub three {
    my $self = shift;
    print "G1 green is ",$self->{three};
}

1;

package G2;

our @ISA = qw(G1);
#use base qw(G1);

sub new {
    my $class = shift;
    my $self = $class->SUPER::new();
    $self->{three} = 90;
    bless $self,$class;
    return $self;
}

sub three {
    my $self = shift;
    print "G2 rox!\n";
    $self->SUPER::three();
}

1;

and the following script:

use G2;

my $ob = G2->new();
$ob->three();

When I run the script, it produces the following error :

Can't locate object method "new" via package "G2" at G2.pm line 8.

If I replace the @ISA line with use base, the script works. I'm trying to override some methods and call the original ones after. What am I doing wrong?

+4  A: 

Because G2.pm needs to include a use G1; line. Without that, G1.pm is never being loaded. If you run with warnings, Perl will tell you this:

$ perl -w t.pl
Can't locate package G1 for @G2::ISA at t.pl line 1.
Can't locate package G1 for @G2::SUPER::ISA at G2.pm line 8.
Can't locate package G1 for @G2::SUPER::ISA at G2.pm line 8.
Can't locate object method "new" via package "G2" at G2.pm line 8.

Notice all the can't locate package G1… errors.

And to be clear, use base 'G1' works because that also does a use G1.

derobert
That was stupid of me, but no matter how many times I read over the code, I haven't noticed that. Thanks!
Geo
Always 'use warnings' and 'use strict'; those two will save you countless hours of debugging.
Drew Stephens
+2  A: 

G2 needs to know about G1, not just the name. Add

require G1;

to G2.pm.

oylenshpeegul