【发布时间】:2009-09-27 11:45:22
【问题描述】:
我选择使用 tie 发现这个:
package Galaxy::IO::INI;
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = {']' => []}; # ini section can never be ']'
tie %{$self},'INIHash';
return bless $self, $class;
}
package INIHash;
use Carp;
require Tie::Hash;
@INIHash::ISA = qw(Tie::StdHash);
sub STORE {
#$_[0]->{$_[1]} = $_[2];
push @{$_[0]->{']'}},$_[1] unless exists $_[0]->{$_[1]};
for (keys %{$_[2]}) {
next if $_ eq '=';
push @{$_[0]->{$_[1]}->{'='}},$_ unless exists $_[0]->{$_[1]}->{$_};
$_[0]->{$_[1]}->{$_}=$_[2]->{$_};
}
$_[0]->{$_[1]}->{'='};
}
如果我删除最后一个“$[0]->{$[1]}->{'='};”,它就不能正常工作。 为什么?
我知道返回值是必需的。但是“$[0]->{$[1]};”也无法正常工作,而且 $[0]->{$[1]}->{'='} 不是全部。
旧帖:
我正在用 Perl 编写一个包来解析 INI 文件。
只是基于Config::Tiny 的东西。
我想保持部分和键的顺序,所以我使用额外的数组来存储顺序。
但是当我使用“$Config->{newsection} = { this => 'that' }; # Add a section”时,我需要重载'=',以便可以将“newsection”和“this”推入数组中。
这是否可以让“$Config->{newsection} = { this => 'that' };”工作而不影响其他部分?
部分代码为:
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = {']' => []}; # ini section can never be ']'
return bless $self, $class;
}
sub read_string {
if ( /^\s*\[\s*(.+?)\s*\]\s*$/ ) {
$self->{$ns = $1} ||= {'=' => []}; # ini key can never be '='
push @{$$self{']'}},$ns;
next;
}
if ( /^\s*([^=]+?)\s*=\s*(.*?)\s*$/ ) {
push @{$$self{$ns}{'='}},$1 unless defined $$self{$ns}{$1};
$self->{$ns}->{$1} = $2;
next;
}
}
sub write_string {
my $self = shift;
my $contents = '';
foreach my $section (@{$$self{']'}}) {
}}
【问题讨论】:
-
可以(并且可能对未来的读者更有帮助)将此作为两个单独的问题发布。
标签: perl oop package overloading tie