top

TOP  RSS  Login

Perl/モジュールを作る

Perl >
package hoge;

sub new {
  my $pkg = shift;
  my $self = bless {} => (ref($pkg) || $pkg);
  return $self;
}

sub hello {
  my $self = shift;
  print "hello";
}


package main;

my $a = hoge->new;
$a->hello;          # hello

print ref($a);      # hoge

クラスを作るクラス

package myclassmaker;
sub new {
  my $pkg = shift;
  my($class) = @_;
  my $self = bless \$class => $pkg;
  return $self;
}

sub add_method {
  my $self = shift;
  my(%codes) = @_;
  while(my($name,$code) = each(%codes)){
    *{"${$self}::${name}"} = $code;
  }
}

package main;
my $hanage = myclassmaker->new("hanage"); # hanageクラスを作ろう

$hanage->add_method(
"new" => sub {
  bless {} => shift;
},
"who" => sub {
  print ref(shift);
});

my $a = hanage->new;
$a->who; # hanage

Last modified:2008/02/02 03:01:56

fa

0.367118