我可以重载Perl =?(使用Tie时出现问题)

Gal*_*axy 2 oop perl overloading package 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]}->{'='};
}
Run Code Online (Sandbox Code Playgroud)

如果我删除最后一个"$ [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{']'}}) {
}}
Run Code Online (Sandbox Code Playgroud)

Ube*_*lex 8

Overload的特殊符号 列出了'='的Perl重载行为.

"="的值是对具有三个参数的函数的引用,即,它看起来像使用中的其他值重载.但是,它不会使Perl赋值运算符重载.这将违背骆驼毛.

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


Vla*_*ala 5

这不完全是JUST运算符重载,但如果你绝对需要这个功能,你可以尝试perl tie:http: //perldoc.perl.org/functions/tie.html


bri*_*foy 5

你知道Config :: IniFiles吗?在你离开之前你可能会考虑重新发明它.通过一些适当的子类,您可以为其添加排序.

另外,我认为你的界面错误了.您正在暴露对象的内部结构并通过魔法分配对其进行修改.使用方法会让您的生活更轻松.