在我的Perl腳本中,我正在收集數據並構建一個hashmap。 hashmap鍵表示字段名稱,值表示我想要插入到相應字段中的值。如何將散列傳遞給子?
構建hashmap,然後傳遞給saveRecord()方法,該方法應該構建SQL查詢並最終執行它。
這裏的想法是更新數據庫一次,而不是每個字段一次(有很多字段)。
問題:我無法將散列圖傳遞給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.
}
在一般情況下,不要使用子程序原型。他們不像其他語言那樣工作。大多數情況下,它們的存在使得模塊作者可以複製內置函數的接口。有關更多信息,請參閱perldoc perlsub。 http://perldoc.perl.org/perlsub.hmtl – daotoad