開発環境
- 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) の12章(データのあるオブジェクト), 12.15(練習問題)1を解いてみる。
1.
やり方の1つ。(「やり方は何通りもある」(TIMTOWTDI(There Is More Than One Way To Do It.)))
コード(TextWrangler)
#!/usr/bin/env perl
use strict;
use warnings;
{ package Animal;
use Carp qw(croak);
sub speak{
my $either = shift;
print $either->name, ' goes ', $either->sound, "\n";
}
sub default_color{'brown'}
sub sound{croak}
sub named{
ref(my $class = shift) and croak;
my $name = shift;
my $self = {Name => $name, Color => $class->default_color };
bless $self, $class;
}
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;
$self->{Name} = shift;
}
sub set_color{
ref(my $self = shift) or croak;
$self->{Color} = shift;
}
}
{ package Horse;
our @ISA = qw(Animal);
sub sound { 'neigh' }
}
{ package Sheep;
our @ISA = qw(Animal);
sub sound{ 'baaaah' }
sub color{ 'white' }
}
my $tv_horse = Horse->named('Mr. Ed');
$tv_horse->set_name('Mister Ed');
$tv_horse->set_color('grey');
print $tv_horse->name, ' is ', $tv_horse->color, "\n";
print Sheep->name, ' colored ', Sheep->color, ' goes ', Sheep->sound, "\n";
入出力結果(Terminal)
$ perl sample.pl Mister Ed is grey an unnamed Sheep colored white goes baaaah $
Perlのオブジェクト指向、C#とかRuby、Pythonに比べていまいちまだ慣れてないかも。。
0 コメント:
コメントを投稿