12. Object Oriented Perl

Created Sunday 27 April 2014

THREE RULES OF PERL OO

Declaring a class:
package Shopper::Personal;
use strict;
use warnings;
sub new {
# more code here
}

An Object Is a Reference That Knows Its Class

OBJECT = bless REFERENCE, CLASSNAME;

A class declaration:
package Shopper::Personal;
use strict;
use warnings;
sub new {

my ($class, $arg_for) = @_;
return bless {
name => $arg_for->{name},
budget => $arg_for->{budget},
}, $class;
}
Initializing an object:
my $aevar = Shopper::Personal->new({
name => 'AEvar',
budget => 100
});
The sub new for passing a list:
sub new {
my ($class, $name, $budget) = @_;
return bless {
name => $name,
budget => $budget,
}, $class;
}
Blessing an array reference:
sub new {
my ($class, $name, $budget) = @_;
return bless [$name, $budget], $class;
}

A Method Is a Subroutine

A class:
package Shopper::Personal;
use strict;
use warnings;
sub new {

my ($class, $arg_for) = @_;
return bless {
name => $arg_for->{name},
budget => $arg_for->{budget},
}, $class;
}
sub get_name {
my $self = shift;
return $self->{name};
}
sub get_budget { # getter
my $self = shift;
return $self->{budget};
}
sub set_budget { # setter
my ($self, $new_budget) = @_;
$self->{budget} = $new_budget;
}
sub budget { # getter and setter
my $self = shift;
if (@_) {
$self->{budget} = shift;
}
return $self->{budget}
}
1;
Creating object and using methods:
my $shopper = Shopper::Personal->new($args); # The class name id passed as the 1st arg to @_
my $budget = $shopper->get_budget(); # The $shopper instance gets passed as the 1st arg to @_
my $budget = $shopper->budget; # get
$shopper->budget($new_budget); # set



Backlinks: