oop.pl

30分シリーズ、16。Perlオブジェクト指向をやってみよう。

Perlは立派なオブジェクト指向言語(OOPL)です。でも、クラスを作ったことはなかったのでやってみました。
お題は、Counterクラス、Personクラスと同じくらい有名なAccountクラス(銀行口座)です。

$ perl oop.pl
init: money = 100
deposit: money = 200
withdraw: money = 0
use strict;
use warnings;
use Data::Dumper;
 
package Account;
 
sub new{
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
 
    my $self = { @_ };
    $self->{'balance'} ||= 0;
 
    bless($self,$class);
    return $self;
}
 
sub deposit{
    my ($self,$money) = @_;
    $self->{'balance'} += $money;
}
 
sub withdraw{
    my ($self,$money) = @_;
    $self->{'balance'} -= $money;
}
 
sub balance{
    my $self = shift;
    return $self->{'balance'};
}
 
package main;
 
sub p($){
    print Dumper($_[0]);
}
 
sub show($$){
    my ($event,$account) = @_;
    my $balance = $account->balance;
    print "$event: money = $balance\n";
}
 
my $my_account = Account->new(balance=>100);
show 'init',$my_account;
 
$my_account->deposit(100);
show 'deposit',$my_account;
 
$my_account->withdraw(200);
show 'withdraw',$my_account;
  • クラスを作るには、パッケージを作ってblessする。blessの訳は聖別する
  • パッケージ内の関数が、メソッドになる。第一引数は自分のクラス
  • 時間がなくてチェックコードを入れられませんでした。いくらでも引き出せます
  • Data::DumperでRubyのp風味