![]()
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
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