When creating module in Perl, use anonymous hash table is recommend.
See the different ways of implementing a module
package A;
require Exporter;
@ISA = qw(Exporter);
@Exporter = qw(test);
my $field;
sub new{
shift;
my $this = {};
$field = shift;
bless $this;
return $this;
}
sub test{
print $field;
}
1;
======================================
package A;
require Exporter;
@ISA = qw(Exporter);
@Exporter = qw(test);
sub new{
shift;
my $this = {};
$this->{field} = shift;
bless $this;
return $this;
}
sub test{
my $this = shift;
print $this->{field};
}
1;
========================================
In the first implementation, if you create more than 1 objects of A, you may found that all these object's 'field' value is the same --- the value is which you created with in last object.
That is because in perl, only blessed fields are packaged into the object. 'field' has not been blessed.
When you creating many A objects, there is only one instance of 'field' in memory. So when you called the objects you created, you will find every objects' field have only 1 value. --------- All these objects share 1 'field.
阅读(891) | 评论(0) | 转发(0) |