2007年9月26日 星期三

Object-Oriented in Perl

如果要在 Perl 5 上寫 OO 的話,就用 Moose.pm 吧!這是一個以 Perl 6 物件模型為基礎的模組,CPAN 上寫道:
Moose is based on the prototypes and experiments I did for the Perl 6 meta-model. However, Moose is NOT an experiment/prototype; it is for real.

如此,你可以類似 Perl 6 的寫法在 Perl 5 上寫 OO. :-)
這種寫法比較直觀,並且功能也比較強大。
package Point;
use Moose; # automatically turns on strict and warnings

has 'x' => (is => 'rw', isa => 'Int');
has 'y' => (is => 'rw', isa => 'Int');

sub clear {
my $self = shift;
$self->x(0);
$self->y(0);
}

package Point3D;
use Moose;

extends 'Point';

has 'z' => (is => 'rw', isa => 'Int');

after 'clear' => sub {
my $self = shift;
$self->z(0);
};
其他對 Moose.pm 的疑問就上 CPAN 的 Moose.pm 看吧! :)

那個..裝 CPAN 模組是這樣裝的:

$ cpan Moose