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.

4
  • what is @monitor_trunks? Is this related to the external command? Commented Oct 19, 2014 at 20:57
  • See stackoverflow.com/questions/12043592/… Commented Oct 19, 2014 at 20:57
  • @martinclayton Given the file handle is for the output from an external command and not a file, that solution will likely return an illegal seek. Commented Oct 19, 2014 at 21:34
  • @NathanFellman monitor_trunks is an array of strings Commented Oct 20, 2014 at 0:06

1 Answer 1

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... 
   }
}  
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.