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

64 views Asked by At

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!

3

There are 3 answers

0
Spartakus On BEST ANSWER

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

}
2
Mark Setchell On

You need something like this:

if (/"bobby"/i){
   $output_textbox->insert("end", "$display\n");
   last;
}

The "last" will quit the loop if "bobby" is found.

0
woolstar On

Instead of using two variables, just use one:

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