Search code examples
perlperltk

Stop after first find within two knowns, print, then continue searching file in perl


I am writing in Perl and would like assistance.

I am trying to write a program to find "Bobby" and print the line of text with "display".

I have already written the program and have it working except one little flaw. If "Bobby" is present multiple times under a single line with "display" in it, it will print that line multiple times. See example below for clarification.

Text file includes...

display ("Blue")
....
....
....
....
display ("Yellow")
....
bobby
....
bobby
bobby
....
display ("Red")
....
.... and so on

My current output is...

display ("Yellow")
display ("Yellow")
display ("Yellow")

It should be:

display ("Yellow")

Here is my relevant code:

while(<$AR>){
  $display = $_ if /display/;
  $output_textbox->insert("end", "$display\n") if /"bobby"/i;
}

I have tried a few different things but with no success. Assistance would be greatly appreciated!


Solution

  • Thanks for your help, I was able to figure it out with the sample you gave me. I was inspired by it. I needed to add a simple counter into my code. It tells my second if statement to only search for bobby right after finding a line that has "display" in it. Perfect! Thanks alot. See code below for full solution.

     while(<$A>){
    
     if (/display/){
     $display = $_;
     $count=0;
     }
    
     if ((/"$bobby"/i) && ($count == 0)){
     $output_textbox->insert("end", "bobby\n");
     $count =1;
     }
    
    }