Coding Domain

Perl Programming: Samples


Employee
This sample demonstrates some Object Orientated Programming with Perl.
Apl.pl
Employee.pm

Anopther simple, but complete Object Package
In perl, there is no new operator, or something else. However, there are some ways of calling a package subroutine, when it hasn't been exported. Second, there is no special syntax for OO in Perl. The bless() function handles the OO thing. You need to bless some reference to an object. You can take an array reference, or an hash reference. The second one is easier to use when you're planning to use inheritance someday.

Person.pm

package Person;

use strict;


#####################################
## Global "static" variables here

#my $staticvar = "value"



#####################################
## Constructor

sub new
{
  # First argument of "new Person(...);" is "Person"
  my $classname = shift;

  # Remaining of the parameters.
  my($name, $street, $homenr, $zip, $country) = @_;

  # Make a hash reference
  # And fill it with instance fields.
  my $object = {};
  $object->{_NAME}    = $name;
  $object->{_STREET}  = $street;
  $object->{_HOMENR}  = $homenr;
  $object->{_ZIP}     = $zip;
  $object->{_COUNTRY} = $country;

  # Make the hash reference package aware.
  # Make it a real object
  return bless $object, $classname;
}

#####################################
## Methods

sub method1
{
  my $this = shift;
  my($param1, $param2, $param3) = @_;
  # Method Body
}

sub method2
{
  my $this = shift;
  my($param1, $param2, $param3) = @_;
  # Method Body
}


#####################################
## Destructor

sub DESTROY
{
  my $this = shift;
  print "Destroying $this\n";
}

1;


Written by Diederik van der Boor at 30 January 2001