開発環境
- 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) の11章(オブジェクト入門), 11.11(練習問題)2を解いてみる。
その他参考書籍
2.
コード(TextWrangler)
sample.pl
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.016;
binmode STDIN, ':utf8';
binmode STDOUT, ':utf8';
{package LivingCreature;
sub speak{
my $class = shift;
if(@_){
print "a $class goes @_\n";
} else {
print "a $class goes ", $class->sound , "!\n";
}
}
}
{package Animal;
our @ISA = qw(LivingCreature);
sub sound{ die }
sub speak {
my $class = shift;
die if @_;
$class->SUPER::speak;
}
}
{package Person;
our @ISA = qw(LivingCreature);
sub sound{ "hmmm" }
}
{package Cow;
our @ISA = qw(Animal);
sub sound{'mooo'}
}
{package Horse;
our @ISA = qw(Animal);
sub sound{'neigh'}
}
{package Sheep;
our @ISA = qw(Animal);
sub sound{'baaaah'}
}
{package Mouse;
our @ISA = qw(Animal);
sub sound{ 'squeak' }
sub speak{
my $class = shift;
$class->SUPER::speak;
print "[but you can barely hear it!]\n";
}
}
print "小動物の名前(Cow/Horse/Sheep/Mouse)を入力(空文字で終了)\n";
my @backyard = ();
while(1){
chomp(my $animal = <STDIN>);
given($animal){
when(/^\s*$/){ last;}
when(/cow/i){$animal = "Cow";}
when(/horse/i){$animal = "Horse";}
when(/sheep/i){$animal = "Sheep";}
when(/mouse/i){$animal = "Mouse";}
default {print "入力を確認してください\n"; next;}
}
push @backyard, $animal;
}
map{ $_->speak } @backyard;
Person->speak;
Person->speak("Hello, Perl!");
入出力結果(Terminal)
$ ./sample.pl 小動物の名前(Cow/Horse/Sheep/Mouse)を入力(空文字で終了) cow horse sheep mouse a Cow goes mooo! a Horse goes neigh! a Sheep goes baaaah! a Mouse goes squeak! [but you can barely hear it!] a Person goes hmmm! a Person goes Hello, Perl! $
0 コメント:
コメントを投稿