1

我在调用带有哈希的构造函数时遇到了一些问题。我得到错误:

“Sumcheck.pm 第 4 行哈希分配中的奇数个元素”。Sumcheck.pm 看起来像这样:

package Sumcheck;

sub new {
    my ($debug, $debug_matches,%checkHash) = @_;
    my $self = {};
    $self->{DEBUG} = $debug;
    $self->{DEBUG_MATCHES} = $debug_matches;
    $self->{CHECKRESULT_OK} = "COMPLIANT"; 
    $self->{CHECKRESULT_ERROR} = "NONCOMPLIANT"; 
    $self->{checkHash} = %checkHash;
    #print %checkHash;

    bless($self);
    return $self;
}
1;

我这样称呼它(只是一个随机哈希):

use Sumcheck;
$debug = 0;
$debug_matches = 1;

%checkHash = (  'The Shining'       => 'Kubrick',
                'Ten Commandments'  => 'DeMille',
                'Goonies'           => 'Donner',);

$sumCheck = Sumcheck->new($debug, $debug_matches, %checkHash);

为什么我会收到此错误?它是如何解决的?

谢谢 :)

4

2 回答 2

2

像这样调用的方法的第一个隐式参数:

MyPackage->someMethod()

是包的名称。例如:

package MyPackage;

sub someMethod {
    print shift;

将产生MyPackage

WRT 对构造函数的想法是:

sub new {
    my $class = shift;  # now your $debug would be $_[0], so:
    my $self = { @_ };  # <- replace this with your own details
    bless $self, $class;
}

您不必完全这样做,但是您现在明白为什么您的哈希有奇数个元素了吗?在Sumcheck::new,$debug不是您认为的那样(检查)。请记住,散列是按字面意思作为列表传递的,如下所示:

name, value, name, value

因此,“Sumcheck”(包名)被放入$debug,0 被放入,$debug_matches然后哈希的第一个元素是 1,导致:

1 => `The Shining`
'Kubrick' => 'Ten Commandments',
'DeMille' => 'Goonies',
'Donner'  =>  # uneven number of elements error

仅供参考,以这种方式调用的对象方法的第一个隐式参数(第二行):

my $obj = Sumcheck->new(..,.);
$obj->someMethod();

将是 $obj,又名。方法中$self

sub someMethod {
    my $self = shift

这是构造函数返回的祝福哈希,new().

于 2012-05-01T11:10:44.927 回答
1

首先,总是在你的程序中使用 use strict和。use warnings

程序没有按你预期的那样工作,因为每当你创建一个类的对象时,第一个参数总是类的实例,所以这样写:

package Sumcheck;
use strict;
use warnings;

   sub new {
   # $checkhash variable holds the reference of the hash.
   my ($class, $debug, $debug_matches,$checkHash) = @_; #$class would hold the instance
   my $self = {};
   $self->{DEBUG} = $debug;
   $self->{DEBUG_MATCHES} = $debug_matches;
   $self->{CHECKRESULT_OK} = "COMPLIANT";
   $self->{CHECKRESULT_ERROR} = "NONCOMPLIANT";
   $self->{checkHash} = %{$checkHash};
   #print %checkHash;
   bless($self);
   return $self;
   }
   my %test = ( abc => "30"); # for testing
   # pass hash as reference
   my $sumcheck = Sumcheck->new('test', 'test20', \%test ); 
   print"$sumcheck->{DEBUG}"; # for testing
   1; 

以上代码将解决您的问题。

于 2012-05-01T11:38:08.133 回答