2011-08-15 121 views
1

在我的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. 
} 
+0

在一般情況下,不要使用子程序原型。他們不像其他語言那樣工作。大多數情況下,它們的存在使得模塊作者可以複製內置函數的接口。有關更多信息,請參閱perldoc perlsub。 http://perldoc.perl.org/perlsub.hmtl – daotoad

回答

8

我清理你的一些代碼。打電話給您的小組時,您的主要問題是沒有使用參考。另外要注意的評論正則表達式這是清理:

代碼:

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) 
+0

非常好,乾淨。謝謝TLP! –

+0

非常歡迎。 – TLP

+1

這是一個很好的重寫。如果你已經解釋了你爲什麼做了你所做的改變,這將是一個很好的答案。由於子參數列表展平,您傳遞參考。你溝渠原型,因爲它們在這裏不可取。你用一個字符類替換了一個交替,因爲它更易於閱讀。您刪除了不必要的轉義,因爲它們也不需要。我沒有足夠的評論來充分解釋每個項目,但至少現在有一些好奇的搜索條件。 – daotoad