開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの機能制限無料版、light版)
- Script言語:Perl
『続・初めてのPerl 改訂版』(Randal L. Schwartz, brian d foy, Tom Phoenix 著、伊藤 直也、田中 慎司、吉川 英興 監訳、株式会社ロングテール/長尾 高弘 訳、オライリー・ジャパン、2006年、ISBN4-87311-305-9) の13章(オブジェクトのデストラクション)、13.8(練習問題)を解いてみる。
1.
コード(TextWrangler)
sample.pl
#!/usr/bin/env perl use strict; use warnings; { package Animal; use Carp qw(croak); sub DESTROY{ my $self = shift; } sub named{ my $class = shift; my $name = shift; my $self = {Name => $name, Color => $class->default_color}; bless $self, $class; } sub default_color {"brown"} sub sound{ die "動物は話をしない";} sub speak{ my $either = shift; print $either->name, " goes ", $either->sound, "!\n"; } sub name{ my $either = shift; ref $either ? $either->{Name} : "an unnamed $either"; } sub color{ my $either = shift; ref $either ? $either->{Color} : $either->default_color; } sub set_name{ ref(my $self = shift) or croak "instance variable needed"; $self->{Name} = shift; } sub set_color{ ref(my $self = shift) or croak "instance variable needed"; $self->{Color} = shift; } } { package Horse; our @ISA = qw(Animal); sub sound{"neigh"} sub DESTROY{ my $self = shift; $self->SUPER::DESTROY; } } { package RaceHorse; our @ISA = qw(Horse); our %STANDINGS; dbmopen(%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)
$ ./sample.pl Billy Boy has standings 1 wins, 0 places, 0 shows, 0 losses. $ ./sample.pl Billy Boy has standings 2 wins, 0 places, 0 shows, 0 losses. $ ./sample.pl Billy Boy has standings 3 wins, 0 places, 0 shows, 0 losses. $ ./sample.pl Billy Boy has standings 4 wins, 0 places, 0 shows, 0 losses. $
途中から何をやってるのか分からなくなりつつも、警告->修正の繰り返しでなんとか完成。
今のところ、Perlの学習はこのあたりからがよく分からなくなってくることを確認できた。
0 コメント:
コメントを投稿