class
クラスメソッドの呼び出しを見てみよう。
2 use strict; 3 4 package Man; 5 sub new(){ 6 my @cals=caller(); 7 print "new:@cals:@_\n"; 8 } 9 sub walk(){ 10 my @cals=caller(); 11 print "new:@cals:@_\n"; 12 } 13 14 package main; 15 Man::walk(); 16 Man->walk(); 17 18 my $man1 = new Man(); 19 my $man2 = Man->new(); 20 $man1->walk();
実行すると
$perl class.pl new:main class.pl 15: new:main class.pl 16:Man new:main class.pl 18:Man new:main class.pl 19:Man Can't call method "walk" without a package or object reference at class.pl line 20.
インスタンスメソッドの呼び出しを見てみよう
1 use strict; 2 3 package Man; 4 sub new(){ 5 my($class)=@_; 6 my $self={}; 7 bless $self; 8 my @cals=caller(); 9 print "new:$class:@cals:@_\n"; 10 $self; 11 } 12 sub walk(){ 13 my($self)=@_; 14 my @cals=caller(); 15 print "new:$self:@cals:@_\n"; 16 } 17 18 package main; 19 Man::walk(); 20 Man->walk(); 21 22 my $man1 = new Man(); 23 my $man2 = Man->new(); 24 $man1->walk();
実行結果
$perl class.pl new::main class.pl 19: new:Man:main class.pl 20:Man new:Man:main class.pl 22:Man new:Man:main class.pl 23:Man new:Man=HASH(0xa051274):main class.pl 24:Man=HASH(0xa051274)
Class::Structでデータ定義して、サブクラスを作ってみる。
1 #--------------------------------- 2 package SubFred; 3 use Class::Struct qw(struct); 4 struct 'Fred' => { 5 one => '$', 6 many => '@', 7 }; 8 9 sub new{ 10 @ISA=qw(Fred); 11 my($class)=@_; 12 my $self={}; 13 bless $self; 14 return $self; 15 } 16 #--------------------------------- 17 package main; 18 use Data::Dumper; 19 $ob = SubFred->new(); 20 21 $ob->one("hmmmm"); 22 $ob->many(0, "here"); 23 $ob->many(1, "you"); 24 $ob->many(2, "go"); 25 print "Just set: ", Dumper($ob) , "\n"; 26 print "Just set: ", $ob->many(2), "\n";
実行結果
Just set: $VAR1 = bless( { 'Fred::many' => [ 'here', 'you', 'go' ], 'Fred::one' => 'hmmmm' }, 'SubFred' ); Just set: go