Reading — step 1 of 5
Learn
~1 min readModules and OOP
A package is Perl's namespace. A module is a file (.pm) that defines a package.
# Counter.pm — a module file
package Counter;
use strict;
use warnings;
sub new {
my ($class, %args) = @_;
my $self = {
count => $args{start} // 0,
};
bless $self, $class;
return $self;
}
sub increment {
my $self = shift;
$self->{count}++;
}
sub get {
my $self = shift;
return $self->{count};
}
1; # modules must return true
bless is what makes an object an object in Perl. It tags a reference with a class name. Method calls on a blessed reference look in that package.
Usage:
use Counter;
my $c = Counter->new(start => 100);
$c->increment;
$c->increment;
print $c->get, "\n"; # 102
Method dispatch — $obj->method(args) is sugar for Class::method($obj, args). The first arg is always the invocant.
Inheritance with @ISA:
package Counter::Bounded;
use parent 'Counter'; # alternative: our @ISA = ('Counter');
sub increment {
my $self = shift;
return if $self->{count} >= $self->{max};
$self->SUPER::increment(); # call parent's version
}
Modern Perl (Moose, Moo) gives you classes with attributes, defaults, types, and roles. For Judge0's plain Perl 5.28, the manual bless style is what works.
For single-file scripts, you can define a package inline:
package Foo {
sub new { ... }
}
my $f = Foo->new();
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…