All pastes #730447 Raw Edit

K0brik

public text v1 · immutable
·published 2007-10-09 06:53 UTC
rendered paste body
Object oriented programming with perl
When we write object oriented style we might have many objects which is based on foreign classes by inheriting and overloading their properties to save ourself from having to rewrite the old functionalities while working in concert. Not only when programming websites but also when we communicate with one another; when we develop one object we often develop the whole picture in many ways at the same time as with sub routines and loops.

Imagine we have a base class of a mobile-phone as the following:

package mobile_phone;

sub new {
  # The Object constructor
  my ($class, $brand, $number) = @_;

  # Define an anonymous hash which will be the object value storage
  my $self = {};

  # Set some values in it
  $self->{brand} = $brand;
  $self->{number} = $number;

  $self->{contact} = {dion => 004561690067, vioce_box => 004523232323};

  # Tell $self that it is now an object of $class
  bless $self, $class;

  # now we can use $self as an object
  $self->add_contact('GF', 0044123123123);
  return $self;
}

sub add_contact {
  my ($self, $key, $value) = @_;
  $self->{contact}{$key} = $value;
  1;
}

sub search_contact {
  my $self = shift;
  my $pattern = shift;
  my @match = grep /$pattern/, keys $self->{contact};
  return @match;
}



Now we want to make a new model of a mobile-phone with some extra func so instead of rewriting the old func we just use it as our base class:

package new_brand;
use base mobile_phone;

sub start_record {
  my $self = shift;
  $self->{record} = 1;
}

sub stop_record {
  my $self = shift;
  $self->{record} = 0;
}



When we do a call to the 'new' constructor using our new_brand class perl will see there are no such sub in our current package and will thereby check our mobile_phone base class / package and find it there instead...


/K0brik