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

Although Perl lets you do this, it's usually a bad idea. It will lead to confusion when people are trying to debug your code and can't figure out where the mysterious packages are coming from. Much simpler to just use multiple files.
  • Comment on Re: Defining classes and inheritance using packages within a single .pl file, without creating modules

Replies are listed 'Best First'.
Re^2: Defining classes and inheritance using packages within a single .pl file, without creating modules
by alw (Sexton) on Jan 03, 2008 at 15:40 UTC
    This modified code demonstrates package inlining and inheritance. For small scripts, I like to inline a package once in a while, escpecially when subclassing a standard module. if I put the main package before the other packages, it doesn't work.
    #!/usr/bin/perl use warnings; no warnings qw/uninitialized/; use strict; use Data::Dumper; ####################### 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 "$this->{TITLE}\tHello $this->{NAME}\t$this->{AGE}\n";; } ####################### package Class2; our @ISA = qw(Class1); sub new { my $class = shift; my $self = $class->SUPER::new(@_); $self->{TITLE} = 'This is Class2'; return $self; } ######################## package main; my $max = Class1->new(NAME=>'Someone Else',AGE=>42); my $max2 = Class2->new(NAME => 'MaxKlokan',AGE=>21) ; $max2->PrintHello(); print Dumper $max; print Dumper $max2; exit;
      If you put the others in a BEGIN block, you can put main first.