Coding Domain

Perl Programming: Samples


Employee.pm
package Employee; # Class name

use strict;


# Static fields here
#my $name;


# Constructor

sub new (@)
{
  my $classname = shift;

  # We don't allow these things:
  #   $x = Employee::new();
  #   $y = $x->new();

  if(! defined $classname) { my@c=caller; die "Syntax error: Class name expected after new at $c[1] line $c[2]\n" }
  if(  ref     $classname) { my@c=caller; die "Syntax error: Can't construct new ".ref($classname)." from another object at $c[1] line $c[2]\n" }



  my $this  = {};

  # Instance fields

  $this->{_NAME} = shift || 'No name';


  # Make the object 'self-aware';
  bless $this, $classname;           # Double argument version to enable Inheritance ;-)

  # Intialize
  # $self->open_log;

  print "Constructor: $this $classname\n";
  return $this;
}


# Methods

sub method
{
  print "Method Called\n";
}

sub getName()   { my $this=shift; return $this->{_NAME} }
sub setName($$) { my $this=shift; $this->{_NAME}=shift; }


# Destructor

sub DESTROY
{
  # End Object
  my $this = shift;
  print "Terminate:   $this " . ref($this) . "\n";
}

1;

__DATA__

=pod

=head1 Employee Object

=over

=item B<5/29/01> - Created

=back

=cut
Code Details
This code is used by Apl.pl. The instance variables (internal variables) are stored in the hash reference. Since an object's method is called as $obj->method() every method receives that hash reference as first parameter. We shift it off. Then we can just perform any task like we did before. Properly, the task depends on the instance variables. You can acces them through $object->{_NAME}.

Perl doesn't help you with hiding any of the instance variables or methods, which is called private methods/variables in other languages. However, I recommand you don't do anything with the instance variables in other parts of your program. Instance variables should be accessed through the methods of the object. When you follow these guide-lines of data-hiding, your program will have less bugs, but you can also change the inner-representation of the data in the object itself without effecting other parts of your program.

Written by Diederik van der Boor at 30 January 2001