2013-06-29 78 views
0

我試圖打印符合我的特定條件的設備列表。當我將所有內容打印到屏幕上時,效果很好。但是,當我將它打印到文件時,它只打印一行。我是新來的Perl,所以任何幫助將不勝感激。由於Perl只打印一行,但打印到屏幕的作品

$dbConnection = &openConnection(); 
# run the "list_device" command via the initial connection 
my $device_list = $dbConnection->list_device(); 
foreach my $listDevices ($device_list->result()) { 
    if ( ($listDevices->model !~ /PIX/) 
     && ($listDevices->model !~ /ASA/) 
     && ($listDevices->model !~ /ACE/) 
     && ($listDevices->driverName !~ /Context/) 
     && ($listDevices->hostName =~ /^ls1.*/i) 
     && ($listDevices->vendor =~ /Cisco/) 
    ) { 
     #create device hash for LS 
     $deviceHash{"deviceID"}   = $listDevices->deviceID; 
     $deviceHash{"deviceType"}  = $listDevices->deviceType; 
     $deviceHash{"vendor"}   = $listDevices->vendor; 
     $deviceHash{"model"}   = $listDevices->model; 
     $deviceHash{"primaryIPAddress"} = $listDevices > primaryIPAddress; 
     $deviceHash{"hostName"}   = $listDevices->hostName; 

     # mapping array 
     my @returnData = (
      "deviceID",   "hostName", 
      "primaryIPAddress", "deviceType", 
      "vendor",   "model" 
     ); 
     open OVERWRITE, ">overwrite.txt" or die $!    
     # loop through the hash and print out the device information 
     foreach my $data (@returnData) { 
      my $returnDataLength = @returnData; 

      if (exists $deviceHash{$data}) { 
           print OVERWRITE $deviceHash{$data} . ","; 
           } 
     } 
     close OVERWRITE; 
    } 
    &closeConnection($dbConnection); 
} 
+0

由於圍繞'open'引用的奇怪引用,該代碼甚至不應該編譯。請注意,''hostname''(數組入口)和''hostName「'(散列鍵)不相同,並且'$ i <@ returnData'將始終爲真,因爲您設置了'$ i'在前一行中爲零。這也是完全不需要的,因爲循環將執行'scalar @ returnData'次,所以即使'$ i'是實際的數組索引,條件總是成立。 – amon

+0

Amon,謝謝你的評論。這是我第一次在這裏發佈,我在複製和粘貼我的代碼在評論框中很困難。我手工輸入了這個密碼,並且錯誤地輸入了「主機名」。我確實把'$ i <@returnData'出來了,所以謝謝 – user2535431

回答

6

你每$data項目編寫一次打開overwrite.txt。它每次都被覆蓋。移動到循環外部。

+0

Daxim,非常感謝你的評論!我已經將循環外部的oppening語句:my @returnData =(「deviceID」,「hostName」,「primaryIPAddress」,「deviceType」,「vendor」,「model」);打開OVERWRITE,「> overwrite.txt」或者死掉$ !; foreach my $ data(@returnData){if(exists $ deviceHash {$ data}){print OVERWRITE $ deviceHash {$ data}。 「」; }}關閉OVERWRITE;但是,它仍然打印一行 – user2535431

+0

@ user2535431 - 您需要將它移到兩個循環之外。或者,您可以以附加模式打開文件:「打開覆蓋」,「>>」,「覆蓋.txt」。一般來說,你也應該[使用三個參數open()命令並避免文件句柄的typeglobs](http://stackoverflow.com/questions/1479741/why-is-three-argument-open-calls-with-autovivified-filehandles -perl-best-pract) – dms

+0

解決了它!謝謝! – user2535431