開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Perl
『続・初めてのPerl 改訂版』(Randal L. Schwartz, brian d foy, Tom Phoenix 著、伊藤 直也、田中 慎司、吉川 英興 監訳、株式会社ロングテール/長尾 高弘 訳、オライリー・ジャパン、2006年、ISBN4-87311-305-9)の11章(オブジェクト入門)の11.11(練習問題)1を解いてみる。
その他参考書籍
1.
コード(BBEdit)
sample.pl
#!/usr/bin/env perl use strict; use warnings; use 5.016; use utf8; binmode STDOUT, ':utf8'; binmode STDIN, ':utf8'; binmode STDERR, ':utf8'; { package Animal; sub speak { my $class = shift; say "a $class goes ", $class->sound, "!"; } } { 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; say "[but you can barely hear it!]"; } } my @backyard = (); say "小動物の名前(Cow/Horse/Sheep/Mouse)を入力(空白で終了)"; while (1) { chomp(my $animal = <STDIN>); if ($animal =~ /^\s*$/) { last; } elsif ($animal =~ /^(Cow|Horse|Sheep|Mouse)$/) { push @backyard, $animal; } else { say "小動物の名前を確認してください。"; } } for (@backyard) { $_->speak }
入出力結果(Terminal)
$ ./sample.pl 小動物の名前(Cow/Horse/Sheep/Mouse)を入力(空白で終了) Mouse Cow Dog 小動物の名前を確認してください。 Sheep Horse a Mouse goes squeak! [but you can barely hear it!] a Cow goes moooo! a Sheep goes baaaah! a Horse goes neigh! $
ちなみにpython3.3の場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 ## Copyright (C) 2013 by kamimura #-*- coding: utf-8 -*- import re # インスタンスを作成しないで同じperlの場合と同じことをしようとしたら # よく分からなくなっちゃったので、違ってインスタンスを使う方法で同じ出力になることをしてみた class Animal: def speak(self): print('a {0} goes {1}!'.format(self.__class__.__name__, self.sound())) class Cow(Animal): def sound(self): return 'moooo' class Horse(Animal): def sound(self): return 'neigh' class Sheep(Animal): def sound(self): return 'baaaah' class Mouse(Animal): def sound(self): return 'squeak' def speak(self): Animal.speak(self) print('[but you can barely hear it!]') animals = {'Animal':Animal, 'Cow': Cow, 'Horse': Horse, 'Sheep': Sheep, 'Mouse': Mouse} backyard = [] print('小動物の名前(Cow/Horse/Sheep/Mouse)を入力(空白で終了)') while True: animal = input() if re.search(r'^\s*$', animal): break; if re.search(r'^(Cow|Horse|Sheep|Mouse)$', animal): backyard.append(animal) else: print('小動物の名前を確認してください。') for animal in backyard: animal = animals[animal]() animal.speak()
入出力結果(Terminal)
$ ./sample.py 小動物の名前(Cow/Horse/Sheep/Mouse)を入力(空白で終了) Mouse Cow Dog 小動物の名前を確認してください。 Sheep Horse a Mouse goes squeak! [but you can barely hear it!] a Cow goes moooo! a Sheep goes baaaah! a Horse goes neigh! $
0 コメント:
コメントを投稿