http://qs321.pair.com?node_id=586646

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

Hello wise Monks!

I am studying Perl OO programming and I have learned how to create classes using modules as packages saved in .pm files. I was wondering whether it is possible to do all that in a single file, so that distributing a perl script would be easier.

I have started experimenting with defining multiple packages in a single script and I seem to be able to create classes and new objects, but so far I had no success trying to implement inheritance.

With the following code I am trying to define two classes: Class1, which is the parent, and Class2 which should inherit from Class1. I was hoping it would work, but actually it doesn't and my Class2 is not a child of Class1 (it cannot find the method PrintHello).

Is this just impossible within a single file or am I missing something?

Here is the code:
#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my $max = Class2->new(NAME => 'MaxKlokan') ; $max->PrintHello(); print Dumper $max; exit; ####################### { package Class1; sub new { my $classname = shift; my $self = {@_}; $self->{NAME} = undef unless $self->{NAME}; $self->{AGE} = undef unless $self->{AGE}; bless($self,$classname); return $self; } sub PrintHello { my $this = shift; print "Hello $this->{NAME}\n";; } } ####################### { package Class2; require Class1; @Class2::ISA = qw(Class1); sub new { my $classname = shift; my $self = Class1->new(); $self->{TITLE} = undef unless $self->{TITLE}; bless($self,$classname); return $self; } }