codescracker


perl

Perl Object Oriented Programming



« Previous Tutorial Next Tutorial »


Object oriented concept in perl is very much based on the references and anonymous arrays and hashes. Let's take a look on the example given below, to get some idea about object oriented programming in perl.

Perl Object Oriented Programming Example

Here is an example program, illustrates the concept and use of object oriented in perl:

#!/usr/bin/perl

# here is the implementation of a simple class in perl

package TestClass;

sub new
{
	print("TestClass::new called\n");
	my $type = shift;
	my $self = {}; 
	return bless $self, $type;   
}

sub DESTROY
{
	print "TestClass::DESTROY called\n";
}

sub TestMethod
{
	print("TestClass::TestMethod called\n");
}

# here is the implementation of inheritance in perl

package MySubClass;

@ISA = qw(TestClass);

sub new
{
	print("MySubClass::new called\n");
	my $type = shift;
	my $self = TestClass->new;
	return bless $self, $type;  
}

sub DESTROY
{
	print("MySubClass::DESTROY called\n");
}

sub TestMethod
{
	my $self = shift;
	$self->SUPER::TestMethod();
	print("   MySubClass::TestMethod called\n");
}

# below is the main program, uses the above classes

package main;

print("Invoke TestClass method\n");

$myObject = TestClass->new();
$myObject->TestMethod();

print("Invoke MySubClass method\n");

$myObject2 = MySubClass->new();
$myObject2->TestMethod();

print("Create a scoped object\n");
{
	my $myObject2 = TestClass->new();
}

# here destructor is called automatically

print("Create and undef an object\n");
$myObject3 = TestClass->new();
undef $myObject3;

print("Fall off the end of the script...\n");

# remaining destructor are called here, automatically

When the above code is executed, it will produce the following output:

Invoke TestClass method
TestClass::new called
TestClass::TestMethod called
Invoke MySubClass method
MySubClass::new called
TestClass::new called
TestClass::TestMethod called
   MySubClass::TestMethod called
Create a scoped object
TestClass::new called
TestClass::DESTROY called
Create and undef an object
TestClass::new called
TestClass::DESTROY called
Fall off the end of the script...
TestClass::DESTROY called
MySubClass::DESTROY called

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test