Ad space (banner)
Lesson 19 / 20

Packages and the basics of object orientation

This lesson covers the package, the basis of object-oriented programming in Perl.

A Perl class is defined as package ClassName; ... 1;. By convention you write the constructor yourself as a subroutine called new.

The sample code defines package Animal;, creates an object from a hash reference in new, and returns the sound it makes from a speak method.

A common early stumble is that there is no built-in class syntax as in other languages — you assemble the object mechanism yourself out of a package and a hash reference. This distinctive shape is Perl's own take on object orientation.

In professional work, more recent Perl code increasingly uses modules such as Moose or Moo to define classes more simply.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Perl directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)