0

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!

amon
  • 57,091
  • 2
  • 89
  • 149
Spartakus
  • 69
  • 1
  • 10

3 Answers3

1

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.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • That gets me close except for one thing. – Spartakus Jan 08 '14 at 02:40
  • Looking at my text file above, if bobby were under display ("Blue") and under display ("Yellow"), only display ("Yellow") would be outputed with the code you provided above. I need my program to out put every line with display that contains bobby under it. – Spartakus Jan 08 '14 at 02:40
0

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

}
Spartakus
  • 69
  • 1
  • 10
0

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 ;
  }
}
woolstar
  • 5,063
  • 20
  • 31