Skip to content

Instantly share code, notes, and snippets.

@rahulkmr
Created February 7, 2010 07:27
Show Gist options
  • Save rahulkmr/297278 to your computer and use it in GitHub Desktop.
Save rahulkmr/297278 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl -w
use strict;
# Lookup the calling object's properties. If not found, lookup for the key in
# base class.
sub dispatch {
my $props = shift;
my $key = shift;
return $props->{$key} || ($props->{'base'} && $props->{'base'}($key))
|| undef;
}
# Person constructor. Takes arbitrary attributes.
sub Person {
my ($props) = @_;
$props->{'dump'} = sub {
print "Hello " . shift() . "\n";
print "Name: $props->{'name'}\n";
print "Age: $props->{'age'}\n";
};
return sub {
dispatch($props, shift());
};
}
# Employee constructor. Extends Person class.
sub Employee {
my ($props) = @_;
# Define base class and instance methods.
$props->{'base'} = Person({'name' => $props->{'name'},
'age' => $props->{'age'}});
$props->{'calc_tax'} = sub {
$props->{'sal'} * .2;
};
# Return consturctor.
return sub {
dispatch($props, shift());
};
}
# Driver code for testing Employee class.
my $emp = Employee({'name' => 'Rahul Kumar', 'age' => 24, 'sal' => 30000});
print $emp->('name') . "\n";
print $emp->('calc_tax')() . "\n";
$emp->('dump')('Rahul');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment