Perl and Object Oriented Programming
“Hereby you reduce the time it takes to code, hence, making you more productive!”In a previous article I mentioned perl modules, and how modularising your code can be a good thing. We’re going to take it a step further this time and discuss Perl Objects. Perl’s definition of an object is very simple: “An Object is a reference to a thingie that belongs to another thingie”.
Says much doesn’t it? What it comes down to – an object is a variable that belongs to a specific class. An example:
package MyThingie;
sub new {
my $that=shift;
my $this=ref($that) || $that;
my $self={};
bless($self, $this);
return $self;
}
Basically, what that did is create an object. You use that one as follows:
use MyThingie;
$thing=new MyThingie;
There you go. You blessed ‘thing’ into the ‘MyThingie’ class. Now, the fun part about objects is that you can move them around at will. If I wanted 10 MyThingie objects, I could create 10 and push them into an array. You can also store variables and methods inside an object, like this:
package MyThingie;
sub new {
my $that=shift;
my $this=ref($that) || $that;
my $self={“thingie” => “something”};
bless($self, $this);
return $self;
}
sub what {
my $self=shift;
my $what=shift;
return $self->{what};
}
Using the above usage example, you would be able to do this:
$something=$thingie->what();
$something would now contain ‘something’. Objects are especially useful for writing skeleton applications, that is, provide all the functions necessary for an application to work. Since you can now easily create multiple frontends for applications using the same object.
“Hereby you reduce the time it takes to code, hence, making you more productive!”
Another fun trait about objects is that they can ‘inherit’ from other objects. Taking the above MyThingie object, we can make another object that inherits from that class by simply using this:
package AnotherThingie;
use MyThingie;
@ISA=qw(MyThingie);
sub that {
my $self=shift;
print(“That’s nice\n”);
}
This AnotherThingie class will inherit all methods from the MyThingie class (including it’s constructor ‘new’ and the ‘what’ function) and adds a new ‘that’ function:
use AnotherThingie;
$anotherthingie=new AnotherThingie;
print($anotherthingie->what);
$anotherthingie->that;
See how easy that was? This is the key to objects. You can now write very complicated applications in a short matter of time!
You can have a base class to access a database for you and give it enough functions to be able to connect, store, and retrieve data. On top of that class, you can build a new class that will do exactly what you want it to do for any given application. Hereby you reduce the time it takes to code, hence, making you more productive!
Reader Comments on this Article:
Comment by:Summary:
StephenI *Still* Don’t Get It! ™