Questions And Answers

More Tutorials

Perl Object oriented

Object-Oriented Perl

In Perl, modules and object-oriented programming go hand in hand. Not all modules are written in an object-oriented fashion, but most are. A couple of definitions are warranted here:

· An object is simply a referenced thingy that happens to know which class it belongs to.
· A class is simply a package that happens to provide methods to deal with objects.
· A method is simply a subroutine that expects an object reference (or a package name, for class methods) as its first argument.

To create an object (or instance of a class), use the class constructor. Usually the class constructor will be a function named “new,” but may be called “Create” for some Win32 modules. For example,
$tri = new Triangle::Right (side1=>3, side2=>4);

The constructor takes a list of arguments describing the properties of the object to be created (see the documentation of the module in question to determine what these should be) and returns a reference to the created object.

An example of a class constructor (internal to the module) is shown below:
package critter; # declare the name of the package

sub new {
my $class = shift; # Get class name
my $self = {}; # Initialize the object to nothing
bless $self, $class; # Declare object to be part of class
$self->_initialize();# Do other initializations
return $self;

Methods (subroutines expecting an object reference as their first argument) may be invoked in two ways:

$object = Packagename->constructor(args);


Methods are simply declared subroutines in the package source file.


In this page (written and validated by ) you learned about Perl Object-oriented . What's Next? If you are interested in completing Perl tutorial, your next topic will be learning about: Perl Common Gateway Interfaces.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.