Classes and Objects

Classes are defined in packages (.pm files) and implement Perl's OO interface. By convention and definition, methods are named as follows:

Trivial Example

 # Trivial class that stores an x and y coordinate
 package Point;
 use strict;

 sub new {
    my $self = { x => 0,    # object data
                 y => 0 };              
    bless($self);           # see 'perldoc -f bless'
    return $self;
 }
 sub get_x {
     my $self = shift;
     return $self->{x};
 }
 sub set_x {
     my ($self, $x) = @_;
     $self->{x} = $x;
 }
 sub get_y {
     my $self = shift;
     return $self->{y};
 }
 sub set_y {
     my ($self, $y) = @_;
     $self->{y} = $y;
 }
 1;

The class is used as follows:

 use Person;
 use strict;

 my $p = Point->new();
 $p->set_x(12);
 $p->set_y(20);
 print("Point at ", $p->get_x(), "/", $p->get_y(), "\n");   # 12/20
 

Exercise

Explain why the above method get_x() can be written as:

 sub get_x { $_[0]->{x}; }

and why the above method set_x() can be written as:

 sub set_x { $_[0]->{x} = $_[1] }

Exercise

Construct a class Person that has the following properties:

Advanced Features