Main Content

Example of OO in Perl

Archive - Originally posted on "The Horse's Mouth" - 2008-06-03 17:32:36 - Graham Ellis

Although Perl 5 doesn't use the words "class", "method" or "object" (or any of the other common OO words), it never the less has a very good OO model indeed - here's the source code of an example, together with the result of running the sample. I'll then give you a few clues!

use train;
use bus;
 
push (@ptl, new train("07:17",2,75));
push (@ptl, new train("06:40",3,60));
push (@ptl, new bus("07:12",2,40));
push (@ptl, new bus("08:10",1,61));
 
for $tranbit (@ptl) {
 print $tranbit;
 print " ",$tranbit->getstaff();
 print " ",$tranbit->getcapacity();
 print " ",$tranbit->getwhat();
 print "\n";
 }
 
__END__
 
The stuff below is comments as held in this
file. Split it out to separate files if you
want to run it!
 
############### train.pm
 
package train;
 
use pt;
@ISA = ("pt");
 
sub getstaff {
 return 1;
 }
 
sub getwhat {
 return ("Metal wheeler");
 }
 
1;
 
############### bus.pm
 
package bus;
 
use pt;
@ISA = ("pt");
 
sub getstaff {
 my ($self) = @_;
 return $$self{nv};
 }
 
sub getwhat {
 return ("Rubber wheeler");
 }
 
1;
 
####################### pt.pm
 
 
package pt;
 
sub new {
 my($class,$time,$nv,$vc)=@_;
 my %info;
 $info{time} = $time;
 $info{nv} = $nv;
 $info{vc} = $vc;
 bless \%info,$class;
 }
 
sub getcapacity {
 my ($self) = @_;
 return $$self{nv}*$$self{vc};
 }
 
1;
 
################## Runs as ...
 
 
j8pl grahamellis$ perl tharness
train=HASH(0x801c70) 1 150 Metal wheeler
train=HASH(0x815f60) 1 180 Metal wheeler
bus=HASH(0x815f9c) 2 80 Rubber wheeler
bus=HASH(0x815ff0) 1 61 Rubber wheeler
j8pl grahamellis$



Right. Now ...

A Perl package is a class
A Perl sub is used to define a method
The list @ISA defines inheritance
Perl's bless function defines the container for variables in the object
my defines a locally scoped variable
-> is used to invoke a method on an object