2009年11月23日

hasを作る。

Moose やら Mouse やらで
has があるけど、どうやって実装してんのかな~?と軽く思ったので
それと同じ事が出来ないか、試してみた。

えっと、ちょっと考えて作っただけなんで、超適当です。

・Elch.pm(Mooseがシカらしいんで、独語でシカにしてみた)


package Elch;

use Exporter;
@ISA = (Exporter);
@EXPORT = qw(has);

my ($class, $file, $line) = caller;

sub has {
my $method = shift;
my ($arg) = @_;

my $routine = {};
if (exists $arg->{'is'}) {
my $is = $arg->{'is'};
if ($is eq 'ro') {
$routine = sub {
die "this is readonly" if scalar @_ > 1;
return $_[0]->{$method};
};
} elsif ($is eq 'rw') {
$routine = sub {
return $_[0]->{$method} = $_[1];
};
}
}

*{"${class}::${method}"} = $routine;
}

*{"${class}::new"} = sub {
my $self = shift;
my (%arg) = @_;

my $member = {};
foreach my $key (keys %arg) {
$member->{$key} = $arg{$key};
}
bless $member, $self;
};

1;

・Mensch.pm


package Mensch;

use Elch;

has name => {
'is' => "ro",
};

1;

・test.pl


#!/usr/bin/perl -w

use strict;
use Mensch;

my $obj = Mensch->new(name => 'anigon');
print $obj->name, "\n";

exit;

こんな感じなのかも。

Posted by anigon at 08:29 PM

トラックバックURL:


http://anigon.net/cgi-bin/mt/mt-tb.cgi/570

「swf[2]。」へ戻る | 「あけてしもたー。」へ進む

上へ戻る