2012年7月29日日曜日

開発環境

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

1.

コード(TextWrangler)

sample.pl

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

{ package Animal;
  sub speak{
    my $class = shift;
    print "a $class goes ", $class->sound, "!\n";
  }
}

{ package Cow;
  our @ISA = qw(Animal);
  sub sound{ "moooo" }
}

{ 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";
  }
}

my @animals = ();

print "小動物の名前(Cow, Horse, Sheep, Mouse)を入力(終了は空白)\n";
while(1){
  chomp(my $animal = <STDIN>);
  if($animal =~ /^\s*$/){
    last if @animals;
    print "1つ以上の小動物の名前を入力してください\n";
    next;
  }
  if($animal =~ /^(Cow|Horse|Sheep|Mouse)$/){
    push @animals, $animal;
    next;
  }
  print "入力内容を確認してください\n";
}

for(@animals){
  $_->speak;
}

入出力結果(Terminal)

$ ./sample.pl
小動物の名前(Cow, Horse, Sheep, Mouse)を入力(終了は空白)

1つ以上の小動物の名前を入力してください
Dog
入力内容を確認してください
Cow
Horse
Sheep
Mouse
Mouse
Horse

a Cow goes moooo!
a Horse goes neigh!
a Sheep goes baaaah!
a Mouse goes squeak!
[but you can barely hear it!]
a Mouse goes squeak!
[but you can barely hear it!]
a Horse goes neigh!
$

0 コメント:

コメントを投稿