2011年8月7日日曜日

開発環境

  • Mac OS X Snow Leopard (OS)
  • TextWrangler(Text Editor) (いずれはBBEditを入手したい!)
  • Script言語:Perl

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

 

1.

コード(TextWrangler)

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

{ package Animal;
  use Carp qw(croak);
  sub named{
    ref(my $class = shift) and croak "class name needed";
    my $name = shift;
    my $self = { Name => $name, Color => $class->default_color};
    bless $self, $class;
  }
  sub default_color {"brown"};
  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;
  @Horse::ISA = qw(Animal);
  sub sound { "neigh" }
}

{ package Sheep;
  @Sheep::ISA = qw(Animal);
  sub sound {"baaaah"}
}

# テスト
my $tv_horse = Horse->named('Mr. Ed');
$tv_horse->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)

C#の学習のおかげか、オブジェクト指向プログラミングに入ってから少し学習速度が上がった気がする!

0 コメント:

コメントを投稿