I have some problems calling a constructor with a hash.
I get the error:
“Odd number of elements in hash assignment at Sumcheck.pm line 4”.
Sumcheck.pm looks like this:
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;
And i call it like this(just a random hash):
use Sumcheck;
$debug = 0;
$debug_matches = 1;
%checkHash = ( 'The Shining' => 'Kubrick',
'Ten Commandments' => 'DeMille',
'Goonies' => 'Donner',);
$sumCheck = Sumcheck->new($debug, $debug_matches, %checkHash);
Why do i get this error? How it is solved?
Thx 🙂
The first implicit argument to a method called like this:
is the name of the package. Eg:
will yield MyPackage.
The idea WRT to constructors is:
You don’t have to do exactly that, but do you see now why your hash has an odd number of elements? In
Sumcheck::new,$debugis not what you think it is (check). Remember, a hash is passed literally as a list like this:So, “Sumcheck” (the package name) gets placed in
$debug, 0 gets placed into$debug_matchesthen the first element of the hash is 1, leading to this:FYI, the first implicit argument to an object method called this way (the second line):
Will be $obj, aka. the
$selfin the method:which is the blessed hash returned by the constructor,
new().