Matt Price
Matt Price

Reputation: 34629

Perl while loop only looping once within a for loop

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.

Upvotes: 0

Views: 627

Answers (1)

Ashalynd
Ashalynd

Reputation: 12573

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... 
   }
}  

Upvotes: 1

Related Questions