奇数子例程参数

时间:2016-04-02 09:10:11

标签: perl hash parameters

我想将哈希值$dbh传递给我的子save2db。但是,我收到一条错误消息:Odd number of elements in hash assignment in file2.pm在这行代码之后:my (%resultHash, $dbh) = (@_);。有人可以向我解释这个错误的原因。提前谢谢!

file1.pl

my $dbh_global = connect2db();
my %hash; ##Assume there are nothing wrong with the hash and it is populated

foreach my $fileName_input (@ARGV){
    NVD::save2db(%hash, $dbh_global);
}

sub connect2db{
    my $driver = "mysql";
    my $database = "test";
    my $dsn = "DBI:$driver:database=$database";
    my $userid = "root";
    my $password = "";

    my $dbh = DBI->connect($dsn, $userid, $password) or die $DBI::errstr;

    return $dbh;  
}

file2.pm

sub save2db{

    my (%resultHash, $dbh) = (@_); # <-Error message occured

    foreach my $resultHash_entry (keys %resultHash){
        my $a= $resultHash{$resultHash_entry}{'a'};
        my $b= $resultHash{$resultHash_entry}{'b'};
        my $c= $resultHash{$resultHash_entry}{'c'};
        my $d= $resultHash{$resultHash_entry}{'d'};

        my $insert_sql = $dbh -> prepare("INSERT INTO `test`.`record`
                                       (`a`, `b`, `c`, `d`)
                                       VALUES
                                       (?, ?, ?, ?)");

        $insert_sql->execute($a, $b, $c, $d) or die $DBI::errstr;
    }

}

1 个答案:

答案 0 :(得分:2)

setTheme(android.R.style.custom_theme); 不是错误,而是警告。 问题出现了,因为当值传递给子程序时,值会一起变平。

让我们考虑你的哈希有一些数据,例如

Odd number of elements in hash assignment

%hash = ("a"=>1,"b"=>2);

然后将值传递给子例程

$dbh_global  = "abc"

Hash总是有一个有价值的键。所以每个哈希都只有偶数据。

将值检索到子程序中,如

 NVD::save2db(%hash, $dbh_global); #the problem is here. 

因此my (%resultHash, $dbh) = (@_); 将包含不均匀的值,三个键和两个值,如此

%resultHash

然后{ a=>1, b=>2, abc #This is the reason of the warning. } 没有任何价值。

所以将行更改为

$dbh

并将值检索到子程序中,如

NVD::save2db($dbh_global, %hash);

否则

使用哈希引用来做到这一点。

my ($dbh,%resultHash) = (@_);