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; } }

In reply to Defining classes and inheritance using packages within a single .pl file, without creating modules by MaxKlokan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.