0

I'm new to perl and struggling with this. How can I make the following code iterate asterisk_Output each run of the for loop? At the moment it completes the while loop on the first iteration of the for loop but not on subsequent ones.

open(asterisk_Output, "/usr/sbin/asterisk -rx \"sip show registry\"|") or die $!;
foreach (@monitor_trunks){  
   while (my $line = <asterisk_Output>) {
       #Perform some action... Such as comparing each line.
   }
}  

The only way I have got it working is by putting the top line within the for loop, but this is un necessary and make multiple calls to the external command.

Matt Price
  • 33,201
  • 6
  • 21
  • 33

1 Answers1

1

At the end of your first loop, the file pointer is at the end of the file. You have to bring it back to beginning if you need another round.

You can try either to rewind the file:

seek(asterisk_Output,0,1);

or (if your logic allows it) to change foreach and while (so that you only read it once):

while (my $line = <asterisk_Output>){  
   foreach (@monitor_trunks) {
       #Perform some action... Such as comparing each line.
   }
}  

The third option would be to read the whole file into an array and use it as an input for your loop:

@array = <asterisk_Output>;

foreach (@monitor_trunks){  
   for my $line (@array) {
   #Perform some action... 
   }
}  
ysth
  • 88,068
  • 5
  • 112
  • 203
Ashalynd
  • 11,728
  • 2
  • 29
  • 35
  • 3
    Given that the file handle is the output from an external command, I expect that your first option is going to return an illegal seek. Therefore, the 2nd or 3rd would be my recommendation. – Miller Oct 19 '14 at 21:32