Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Inheritance in the same file

by yoda54 (Monk)
on Jun 11, 2013 at 07:21 UTC ( #1038206=perlquestion: print w/replies, xml ) Need Help??

yoda54 has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

I have a small inheritance hierarchy in the same file, but how come B can't seen to see A?

Thanks!

I keep getting:

Can't locate object method "new" via package "B" at ./example line 7.

#!/usr/bin/perl use strict; use warnings; require B; my $a = B->new(); package A; use strict; use warnings; sub new { my ($class, %args) = @_; my $self = bless { }, ref($class) || $class; return $self; } 1; package B; use strict; use warnings; require A; @B::ISA = qw(A); sub _init { my ($self, %args) = @_; $self->{_title} = $args{title} || undef; } 1;

Replies are listed 'Best First'.
Re: Inheritance in the same file
by Corion (Pope) on Jun 11, 2013 at 07:43 UTC

    B is an already existing package.

    require will try to load a file from disk and fail if that file does not exist.

    The combination means that some package "B" gets loaded from disk, so your require B never fails.

    Your real problem is one of initializsation. @B::ISA gets initialized after your main program has run, so the inheritance chain is never set up.

    I recommend reordering your source file to have the main program at the bottom, or better, move the packages out into separate files.

      Alternatively, you can wrap the class code in a BEGIN block. That will ensure that your classes are initialized before the main code gets run. You don't need "require" or '1;' when the code is in the same file. Also, 'use strict' is lexically scoped, so you really only need to say it at the top.

      #!/usr/bin/perl use strict; use warnings; my $a = B->new(); BEGIN { package A; sub new { my ( $class, %args ) = @_; my $self = bless {}, ref($class) || $class; return $self; } package B; @B::ISA = qw(A); sub _init { my ( $self, %args ) = @_; $self->{_title} = $args{title} || undef; } }

      stephen

        Thank you!
      Thanks much!!!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1038206]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2020-07-08 08:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?