2013-06-29 135 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