Mooseが流行っているらしいじゃねえか

http://search.cpan.org/~stevan/Moose-0.43/lib/Moose.pm

インストールしてみて、ほんのちょっぴり使ってみた。

Numという親クラスは、numberというInt型のリードオンリープロパティアクセサを持っていて、sayというメソッドを実行すると、numberプロパティの中身を表示する。

Numから継承した、One、Two、Threeは、numberプロパティアクセサのデフォルト値をそれぞれ、1、2、3でオーバーライドする。

Twoのみ、numberプロパティアクセサは、読み書き可能としてみた。

#!/usr/bin/perl
package Num;
use strict;
use warnings;
use Moose;

has 'number' => (is => 'ro', isa => 'Int', default => undef);

sub say {
    my $self = shift;

    local $\ = "\n";
    print $self->number;
}

package One;
use strict;
use warnings;
use Moose;

extends 'Num';

has 'number' => (default => 1);

package Two;
use strict;
use warnings;
use Moose;

extends 'Num';

has 'number' => (is => 'rw', default => 2);

package Three;
use strict;
use warnings;
use Moose;

extends 'Num';

has 'number' => (default => 3);

package main;
use strict;
use warnings;
use Data::Dumper;

my $one   = new One;
my $two   = new Two;
my $three = new Three;

$one->say;
$two->say;
$three->say;

$one->number(10); # Cannot assign a value to a read-only accessor at (eval 70) line 1 Num::number('Three=HASH(0x91826b8)', 30) called at test.pl line 58
$two->number(20); # これはおっけ(でも実行されない)。
$three->number(30); # これはいわずもがな。

実行結果。

1
2
3
Cannot assign a value to a read-only accessor at (eval 70) line 1
        Num::number('One=HASH(0x8691cb8)', 10) called at test.pl line 56

ああ、確かにこりゃラクチンだわ。プロパティアクセサオーバーライドがあるってのがいいなぁ。

おれの期待通りにすんなり動いてくれた。