1. Perl
  2. Object Oriented
  3. base

Inherit class using base module

I explained class inheritance using @ISA. However, this method touches some a package variable, so it's kind of weird to anyone who has learned inheritance syntax in other languages.

There is a little more straightforward way to express inheritance. That's how to use base module.

base module

Perl inheritance is better to use the base module than to use @ISA. Internally, the base module does the same thing by touching @ISA, but it hides touching @ISA.

Also, since @ISA is operated at compile time, it is convenient when writing class definition and object creation in one script.

Now let's rewrite inheritance using @ISA using base.

use strict;
use warnings;

# Use the button class.
my $button = Button->new;
print $button->x;


# Component class
package Component;
sub x {return 5}

# Button class
package Button;
# Inheritance
use base 'Component';

sub new {bless {}, 'Button'}

Write use base and pass the class name you want to inherit as an argument. Because use base is executed at compile time

my $button = Button->new;

There is no problem even if you write on the upper side. I would like to write the example from here using the base module.

Related Informatrion