我选择用领带和发现这样的:

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”和“这个”可以在阵列中被推动。

这可能使“$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{']'}}) {
}}
有帮助吗?

解决方案

这是不完全JUST运算符重载,但如果你确实需要此功能,您可以尝试一个perl领带: http://perldoc.perl.org/functions/tie.html

其他提示

用于重载特殊符号 列出的Perl的重载为“=”的行为。

  

为“=”是一个参照本发明的功能与三个参数,该值即,它看起来像在使用过载的其它值。但是,它不超载Perl的赋值操作符。这将违背驼绒。

所以,你可能需要重新考虑你的方法。

你了解配置:: IniFiles ?你去关闭和重新创造它之前,你可能会考虑这一点。随着一些适当的子类,你可以添加订购吧。

另外,我觉得你有错误的接口。你暴露你的对象的内部结构,并通过神奇的任务修改它。使用方法将使你的生活变得更轻松。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top