Creating A Class in Perl With Public Methods

This example demonstrates how to create a class in Perl and use accessor methods such as 'get' and 'set' to access variables/attributes. Also demonstrates 'blessing' with the perl function bless. This is very useful as it allows the encapsulation of related data and helps to neaten code.

Let us have a look at the example. It is self explanatory. We create two files. One file will be named ComplexNumber.pm and the other run.pl. Make sure both these files are in the same place. FYI: The class models a complex number with real and imaginary components - not important

ComplexNumber.pm is the Perl package or 'class'
 1. package ComplexNumber;
 2. 
 3. sub new {
 4.     my $class = shift;
 5.     my $self = {
 6.         REAL => shift,
 7.         IMAGINARY => shift
 8.     };
 9.     bless $self, $class;
10.     return $self;
11. }
12. 
13. sub getReal(){
14.     my $self = shift;
15.     return $self->{REAL};
16. }
17. 
18. sub setReal(){
19.     my $self = shift;
20.     $self->{REAL} = shift;
21. }
22. 
23. sub printNumber(){
24.     my $self = shift;
25.     print "$self->{REAL} + $self->{IMAGINARY}i\n";
26. }
27. 1;
Hide line numbers


run.pl is the script that will instantiate the class and call some of the getter and setter methods.
 1. use ComplexNumber;
 2. 
 3. 
 4. my $num1 = ComplexNumber->new(1,2);
 5. my $num2 = ComplexNumber->new(3,4);
 6. 
 7. $num1->printNumber();
 8. $num2->printNumber();
 9. 
10. print "Changing real from ".$num1->getReal()." to 20\n";
11. $num1->setReal(20);
12. 
13. $num1->printNumber();
Hide line numbers

No comments: