CLASSES

Perl provides a very simple method for creating classes and allowing you to create objects off of those classes. We can summarize Perl's approach to creating classes in three points:

  • An object is simply a reference.

  • A class is simply a package.

  • A method is simply a subroutine.

For example, to create a new class and the constructor method required to create a new object, in this case an object for tracking banking accounts, is as simple as:

package Account;
sub new
{
    my ($package, $name, $balance) = @_;
    my $self = {'Name' => $name,
                'Balance' => $balance};
    bless $self, $package;
    return $self;
}

sub deposit
{
    my ($self, $value) = @_;
    $self->{'Balance'} += $value;
}

sub withdraw
{
    my ($self, $value) = @_;
    $self->{'Balance'} -= $value;
}

Get Perl To Python Migration now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.