1

我正在尝试为我创建的类覆盖相等 (==) 运算符,但我现在遇到了一个问题,我看不到出路。任何帮助将不胜感激。

这是new()该课程的子:

sub new
{
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
    my $self = {@_};
    bless($self, $class);
    return $self;
}

这是相等运算符重载:

use overload ('==' => \&compare);
sub compare
{
    my ($lhs, $rhs, $swap) = @_;
    my $lhsSize = keys(%{$lhs});
    my $rhsSize = keys(%{$rhs});
    if($lhsSize != $rhsSize) { return 0; }  # If objects don't have the same number of fields, they cannot be identical

    while (my ($lhsKey, $lhsValue) = each(%{$lhs})) # Loop through the fields
    {
        my $rhsValue = %{$rhs}->{$lhsKey};
        print("Key: $lhsKey Comparing $lhsValue with $rhsValue");
        if($rhsValue ne $lhsValue)
        {
            return 0;
        }
    }
    return 1;
}

在这里,我得到第Using a hash as a reference is deprecated at Cashflow.pm line 43.43 行所在的错误my $rhsValue = %{$rhs}->{$lhsKey};。然后我发现这个线程建议解决方案是删除->但如果我将行更改为my $rhsValue = %{$rhs}{$lhsKey};我得到语法错误。

您可能会说,我不是 Perl 专家,但我不明白为什么这不起作用。

提前感谢您的帮助。

标记

4

3 回答 3

4

解决方案是(可能)删除哈希取消引用%{ ... }

my $rhsValue = $rhs->{$lhsKey};

使用取消引用到哈希的唯一原因%{ ... }是如果您想要一个项目列表,例如在制作副本时:

my %hash = %$rhs;

或者当使用某些哈希特定函数时

keys %$rhs;
于 2013-10-25T13:01:02.400 回答
2

错误在while循环中:

my $rhsValue = %{$rhs}->{$lhsKey};

错误是因为$rhs是一个祝福的哈希引用,应该像这样访问它:

my $rhsValue = $rhs->{$lhsKey}; # or $$rhs{$lhsKey}

所以我会这样:

while (my ($lhsKey, $lhsValue) = each(%{$lhs})) # Loop through the fields
{
    return 0 if ! defined $rhs->{$lhsKey};

    my $rhsValue = $rhs->{$lhsKey};
    return 0 if $rhsValue ne $lhsValue;

}
于 2013-10-25T13:00:54.527 回答
1

如果它是

%hash
$hash{$key}

对于哈希,它是

%{ $hash_ref }
${ $hash_ref }{$key}

用于哈希参考。对于简单的引用表达式,花括号是可选的。

%$hash_ref
$$hash_ref{$key}

您也可以将后者写为

$hash_ref->{$key}

%{$rhs}->{$lhsKey}没有意义,因为%在哈希等价物 ( $rhs{$lhsKey}) 中没有。

参考:

于 2013-10-25T15:24:16.923 回答