如何将哈希传递给子?

时间:2011-08-15 14:59:54

标签: sql perl hash parameter-passing dbi

在我的perl“脚本”中,我正在收集数据并构建一个hashmap。 hashmap键表示字段名称,值表示我要插入相应字段的值。

构建hashmap,然后传递给saveRecord()方法,该方法应该构建SQL查询并最终执行它。

这里的想法是更新数据库一次,而不是每个字段更新一次(有很多字段)。

问题:我无法将hashmap传递给sub,然后将字段和值从hashmap中拉出来。此时我的键和值是空白的。我怀疑数据在传递给子时会丢失。

脚本的输出表示没有键,没有值。

需要帮助将数据传递给sub,以便让我将其拉回(如图所示) - join()

谢谢!

代码段:

for my $key (keys %oids) {
        $thisField = $key;
        $thisOID = $oids{$thisField};
        # print "loop: thisoid=$thisOID field=$thisField\n";

        # perform the SNMP query.
        $result = getOID ($thisOID);
        # extract the information from the result.
        $thisResult = $result->{$thisOID};

        # remove quotation marks from the data value, replace them with question marks.
        $thisResult =~ s/\"|\'|/\?/g;

        # TODO: instead of printing this information, pass it to a subroutine which writes it to the database (use an update statement).
        # printf "The $thisField for host '%s' is '%s'.\n", $session->hostname(), $result->{$thisOID};

        # add this key/value pair to the mydata hashmap.
        $mydata{$thisField} = $thisResult;

        # print "$thisField=$thisResult\n";
}


# write one record update for hashmap %mydata.
saveRecord (%mydata);


# write all fields to database at once...
sub saveRecord ($) {
        my $refToFields=shift;


        my @fieldlist = keys %$refToFields;
        my @valuelist = values %$refToFields;
        my $sql = sprintf ("INSERT INTO mytable (%s) VALUES (%s)",join(",",@fieldlist), join(",",@valuelist) );

        # Get ID of record with this MAC, if available, so we can perform SQL update
        my $recid = getidbymac ($MAC);

        print "sql=$sql\n";
    # TODO: use an insert or an update based on whether recid was available...
        # TODO: ID available, update the record
        # TODO: ID not available, insert record let ID be auto assigned.
}

1 个答案:

答案 0 :(得分:8)

我稍微清理了你的代码。你的主要问题是在调用你的sub时没有使用引用。另请注意已清除的注释正则表达式:

<强>代码:

use strict;
use warnings;

# $thisResult =~ s/["']+/?/g;
my %mydata = ( 'field1' => 12, 'field2' => 34, );

saveRecord (\%mydata); # <-- Note the added backslash

sub saveRecord {
    my $ref = shift;
    my $sql = sprintf "INSERT INTO mytable (%s) VALUES (%s)",
        join(',', keys %$ref),
        join(',', values %$ref);
    print "sql=$sql\n";
}

<强>输出:

sql=INSERT INTO mytable (field1,field2) VALUES (12,34)