Created
February 7, 2010 07:27
-
-
Save rahulkmr/297278 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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