2012年7月31日火曜日

開発環境

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

1.

コード(TextWrangler)

sample.pl

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

{ package Animal;
  use Carp qw(croak);
  sub named{
    my $class = shift;
    my $name = shift;
    my $self = {Name => $name, Color => $class->default_color};
    bless $self, $class;
  }
  sub default_color {"brown"}
  sub sound{ die "動物は話をしない";}
  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;
  our @ISA = qw(Animal);
  sub sound{"neigh"}
}

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

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)

$ ./sample.pl
Mister Ed is grey
an unnamed Sheep colored brown goes baaaah
$

0 コメント:

コメントを投稿