只需阅读perltooc,其中作者解释同名元对象。我有一些关于它的问题,我没有通过搜索找到...关于同名元对象的问题
1. 哈希必须被命名为对象,但如果对象的名称如果像My :: Good :: Class ,它的同名散列的名称是什么? 我想:
package My::Good::Class
our %Class = (some_data => 1);
sub getEpoHash {
my $class = shift;
my $var = ref($class) || $class;
no strict 'refs';
return \%$var;
}
在我写我们班%的情况下
...; - 它不起作用,但如果我写%My :: Good :: Class = ...; - 有用。我不明白!在这种情况下,Class是My :: Good包的散列...或者什么?!
2. 在文章的例子中有如何使用同名的元对象来创建一个monadic类。但是所有的例子都是用严格写的!在使用$ self之前,我是否必须在每个函数中插入没有严格的'refs',还是有其他方法使用strict来重写?
这里是例子:
package Cosmos;
%Cosmos =();
# accessor method for "name" attribute
sub name {
my $self = shift;
$self->{name} = shift if @_;
return $self->{name};
}
# read-only accessor method for "birthday" attribute
sub birthday {
my $self = shift;
die "can't reset birthday" if @_; # XXX: croak() is better
return $self->{birthday};
}
# accessor method for "stars" attribute
sub stars {
my $self = shift;
$self->{stars} = shift if @_;
return $self->{stars};
}
# oh my - one of our stars just went out!
sub supernova {
my $self = shift;
my $count = $self->stars();
$self->stars($count - 1) if $count > 0;
}
# constructor/initializer method - fix by reboot
sub bigbang {
my $self = shift;
%$self = (
name => "the world according to tchrist",
birthday => time(),
stars => 0,
);
return $self; # yes, it's probably a class. SURPRISE!
}
# After the class is compiled, but before any use or require
# returns, we start off the universe with a bang.
__PACKAGE__ -> bigbang();
关于同名散列的描述 - 是的,它是严格的,但关于monadic类它不是。 http://perldoc.perl.org/perltooc.html#Monadic-Classes 这是奇怪的..那么我应该如何创建与'复杂'名称的包的同名散列,如果'简单'我刚刚把其名称。 包Some_Class;我们的%Some_Class 包My :: Good :: Class;我们的%My :: Good :: Class; #语法错误! 对不起,不明白它是如何工作在:( – Peter 2012-01-07 00:44:46