Perl - 构造函数中哈希赋值中的奇数个元素

时间:2012-05-01 11:01:27

标签: perl hash constructor

我在使用哈希调用构造函数时遇到一些问题。 我收到错误:

“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);

为什么我会收到此错误?怎么解决?

Thx:)

2 个答案:

答案 0 :(得分: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

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

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

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

sub someMethod {
    my $self = shift

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

答案 1 :(得分:1)

首先,在您的程序中始终使用 use strictuse 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; 

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