Perlで、クラス作成用のモジュール等を使わずにごく簡単にクラスを作成する時のサンプル。
package Person;
use strict;
use warnings;
use Carp;
my @ATTRS = qw( name mail url );
# make accessors
for my $attr (@ATTRS) {
my $acc_ref = sub {
@_ > 1
? $_[0]->{$attr} = $_[1]
: $_[0]->{$attr};
};
no strict 'refs';
*{$attr} = $acc_ref;
}
# constructor (argument is hash ref.)
sub new {
my $self = {};
$self->{$_} = $_[1]->{$_} for @ATTRS;
bless $self, $_[0];
}
sub inspect {
my ($self) = @_;
printf "[%s]\n", ref $self;
for my $attr (@ATTRS) {
printf "%10s => %s\n", $attr, $self->$attr;
}
}
1;
動作確認用スクリプト
use strict;
use warnings;
use Person;
my $john = Person->new({
name => 'john',
mail => 'john@example.com',
url => 'http://john.example.com',
});
$john->inspect();
my $paul = Person->new();
$paul->name('paul');
$paul->mail('paul@example.com');
$paul->url('http://example.com/~paul/');
$paul->inspect();
YukiWiki 2.1.2
(C) 2000-2004 by Hiroshi Yuki.