title: How can I print all the lines between the previous and next empty lines when a match is found?
body: <p>I've racked my brain trying to come with a solution but in vain. Any guidance would be appreciated. </p>
  
  <pre><code>_data_
  mascot
  friend
  ocean
  \n
  parsimon
  **QUERY**
  apple
  \n
  jujube
  \n
  apricot
  maple
  **QUERY**
  rose
  mahonia
  \n
  </code></pre>
  
  <p>....Given the search keyword is <strong>QUERY</strong>, it would output:</p>
  
  <pre><code>parsimon
  **QUERY**
  apple
  
  apricot
  maple
  **QUERY**
  rose
  mahonia
  </code></pre>
  
  <p>I wrote a code that doesn't work as I would like:</p>
  
  <pre><code>#!/usr/bin/perl
  
  use strict; 
  use warnings;
  
  open my $fh, '&lt;', 'FILE' or die "Cannot open: $!";
  my @file = &lt;$fh&gt;;
  close $fh;
  
  for (0 .. $#file) {   # read from the first line to the last
    if($file[$_] =~ /QUERY/){  # if the contents of a particular line matches the query pattern
          my $start = $_-- until $file[$_--] =~ /^$/; #check the previous line for an empty line. continue until success. store the index of the empty line to $start.
          my $end = $_++ until $file[$_++] =~ /^$/; #check the next line for an empty line. continue until sucess. store the index of the empty line to $end.
  
  print "\n @file[$start..$end]"; #print all lines between the stored indexes
  }
  }
  </code></pre>
  
  <p>I also tried something like this but there was syntactic error:</p>
  
  <pre><code>if($file[$_] =~ /QUERY/){
          my $start = $_-4 if $file[$_-4] =~ /^$/;
        continue  my $start = $_-3 if $file[$_-3]=~/^$/;
    ------
  my $end = $_+4 until $file[$_+4] =~ /^$/;
  .....
  
  print "\n @file[$start..$end]";
  }
  .....
  </code></pre>
  
  <p>Seems that the only good thing that I've so far succeeded in achieving is I can print everything between the matching lines and next empty lines using the following code:</p>
  
  <pre><code>for (0 .. $#file) {
    if($file[$_+1] =~ /QUERY/) {
     print $file[$_] until $file[$_++]=~/^$/;
  </code></pre>
  
  <p>Can someone point me in the right direction?
  Thanks!</p>
  
  <p>Mike</p>
  
  <p><strong>Edit</strong></p>
  
  <p>I think brian d foy's solution to my problem is the best. By best I mean the most efficient. But Jeff's solution is the most helpfult and I benefit a lot especially from his detailed line-by-line explanations and what's even better, using his code, with only a few tweaks, I can do something else, for example, print all lines between the lines starting with a digit when a pattern is found. And Kinopiko's code is the very code I was hoping to be able to write.</p>