Interesting.

The root cause is that perl has read your entire script from start to finish and compiled it, so that Class2::new exists as a method for you to call.

What hasn't happened at the time you are trying to execute $max->printHello is that the line @Class2::ISA = qw(Class1) hasn't been executed yet...simply because it is further down the script.

Normally, you pull in an external module as a seperate file with a use directive. This is like a require with a BEGIN block around it, which runs all the code in the module as well as compiling it.

You could fix this issue by either moving the { package ... } sections before your code or putting a BEGIN { ... } block around your package definitions.

However, I'd personally do neither of those. The best way these days to declare inheritance is use base, which also has the handly property of being a compile-time construct.

Also - to address your other issues, perl OO gets quite a bit nicer if you start to use some of the CPAN modules. The problem is working out which ones to use :-).

Class::Accessor is quite good, and Moose looks like it might be the way of the future. There is a discussion about this here from April of this year.


In reply to Re: Defining classes and inheritance using packages within a single .pl file, without creating modules by jbert
in thread 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.