| Next | February 2001 | Slide #15 |
Accessor methods provide a natural place to perform argument checking
package Bank_Account;
sub new {
my ($class, $owner, $initial_balance) = @_;
my $self = { OWNER => $owner, BALANCE => $initial_balance };
bless $self => Bank_Account;
}
sub deposit {
my ($self, $amount) = @_;
$self->{BALANCE} += $amount;
}
sub withdraw {
my ($self, $amount) = @_;
croak "Overdrawn" if $amount > $self->{BALANCE};
croak "Can't withdraw negative amount" if $amount < 0;
$self->{BALANCE} -= $amount;
}
sub balance {
my ($self) = @_;
return $self->{BALANCE};
}
To use this:
my $freds_acc = Bank_Account->new('Fred', 100.00);
$freds_acc->deposit(50.00);
$freds_acc->withdraw(87.28);
print "Fred's balance is ", $freds_acc->balance, "\n";
$freds_acc->withdraw(-1000); # Fatal error
| Next | ![]() |
Copyright © 2001 M-J. Dominus |