| Next | Higher-Order Perl | 121 |
sub make_bank_account {
my ($name, $balance) = @_;
return sub {
my $method = shift;
if ($method eq 'deposit') {
$balance += shift();
} elsif ($method eq 'withdraw') {
my $amount = shift;
die "Negative withdrawal for account `$name'\n"
if $amount < 0;
die "Account `$name' overdrawn\n"
if $amount > $balance;
$balance -= $amount;
} elsif ($method eq 'balance') {
return $balance;
} elsif ($method eq 'name') {
return $name;
} else {
die "Unknown method `$method' in bank account object";
}
};
}
my $freds_account = make_bank_account('Fred', 100.00);
$freds_account->('deposit', 50.23);
$freds_account->('withdraw', 20.11);
$b = $freds_account->('balance');
Looks like objects, smells like objects
It's objects all right!
| Next | ![]() |
![]() |
Copyright © 2006 M. J. Dominus |