Defining Packages
Let's get started with the basics of packages in this lesson.
Syntax for defining packages
We define our own package by starting with the keyword package followed by the name you want to give to your new package. It should end with the ; sign. We use 1; at the end of the package definition to mark the end of the scope.
Here’s the general syntax:
Example snippet
Here’s an example snippet of a package named Shape.
Explanation
Line 3:
- The
sub newmethod here is an initializer subroutine to hold the member variables. We have defined this because we can only initialize member variables if we define an initializer subroutine first.
Line 4:
- The
my $class = shift;statement stores the class nameShapein a local scalar variable called$class, usingshift.
Line 5-9:
- The
my $selfhere is a hash which is used to store key/value pairs of the passed member variablessidesandname.
Line 11:
- The
bless $self, $class;turns the hash reference stored in$selfinto aShapeobject by “blessing” it into theShapeclass.
Line 12:
return $self;statement returns the newly created object.
Adding methods to a package
Explanation
We have declared a method named Description, which prints the name and sides of the Shape.
To access the object for which this method is called, we use $self and point it to the respective object using @_.
Creating the object
Once the class Shape is defined, you can create an object of the Shape class. For example, an instance of a Shape, say, a Square would be an object and so would be the other instances of the class Shape like Circles or Triangles, etc. Hence, you can have multiple instances of a package, just like you can have multiple Shapes.
Here’s the basic syntax of creating an object of a class:
Here, we use the new keyword to create a new instance of the class.
In the case of our Shape class example, this is how we’d make an object:
Creating multiple objects of a class
We can create two more objects of the same class, i.e., a hexagon and a triangle:
Let’s look at the illustration for a better understanding: