2011年8月8日月曜日

開発環境

  • Mac OS X Snow Leopard (OS)
  • TextWrangler(Text Editor) (いずれはBBEditを入手したい!)
  • Script言語:Perl

『続・初めてのPerl 改訂版』(Randal L. Schwartz, brian d foy, Tom Phoenix 著、伊藤 直也、田中 慎司、吉川 英興 監訳、株式会社ロングテール/長尾 高弘 訳、オライリー・ジャパン、2006年、ISBN4-87311-305-9) の13章(オブジェクトのデストラクション), 13.8(練習問題)、1を解いてみる。

 

1.

コード(TextWrangler)

#!/usr/bin/perl
use strict;
use warnings;

{ package Animal;
  use Carp qw(croak);
  sub named{
    ref(my $class = shift) and croak "class name needed";
    my $name = shift;
    my $self = { Name => $name};
    bless $self, $class;
  }
  sub name{
    my $either = shift;
    ref $either
      ? $either->{Name}
      : "an unnamed $either";
  }
  sub DESTROY{
    my $self = shift;
    print '[', $self->name, " has died.]\n";
  }
}

{ package Horse;
  @Horse::ISA = qw(Animal);
  sub DESTROY{
    my $self = shift;
    $self->SUPER::DESTROY;
    print "[", $self->name, " has gone off to the glue factory.]\n";
  }
}

{ package RaceHorse;
  @RaceHorse::ISA = qw(Horse);
  dbmopen (our %STANDINGS, "standings", 0666) or die;  
  sub named{
    my $self = shift->SUPER::named(@_);
    my $name = $self->name;
    my @standings = split ' ', $STANDINGS{$name} || "0 0 0 0";
    @$self{qw(wins places shows losses)} = @standings;
    $self;
  }
  sub DESTROY{
    my $self = shift;
    $STANDINGS{$self->name} = "@$self{qw(wins places shows losses)}";
    $self->SUPER::DESTROY;
  }
  sub won { shift->{wins}++;}
  sub placed {shift->{places}++;}
  sub showed {shift->{shows}++;}
  sub lost{shift->{losses}++;}
  sub standings{
    my $self =shift;
    join ", ", map "$self->{$_} $_", qw(wins places shows losses);
  }
}

my $runner = RaceHorse->named('Billy Boy');
$runner->won;
print $runner->name, ' has standings ', $runner->standings, ".\n";

入出力結果(Terminal)

ググりつつ、解答を見つつ、なんとかプログラムを完成させた。問題のプログラムを4回実行すると、4回の勝利が表示されたしとりあえずあってるのかな〜

0 コメント:

コメントを投稿