title: Perl search for first occurrence of pattern in directory
body: <p>I have a directory with a list of image header files of the format</p>
  
  <pre><code>image1.hd
  image2.hd
  image3.hd
  image4.hd
  </code></pre>
  
  <p>I want to search for the regular expression <code>Image type:=4</code> in the directory and find the file number which has the first occurrence of this pattern. I can do this with a couple of pipes easily in bash:</p>
  
  <pre><code> grep -l 'Image type:=4' image*.hd | sed ' s/.*image\(.*\).hd/\1/' | head -n1
  </code></pre>
  
  <p>which returns 1 in this case.</p>
  
  <p>This pattern match will be used in a perl script. I know I could use</p>
  
  <pre><code>my $number = `grep -l 'Image type:=4' image*.hd | sed ' s/.*image\(.*\).hd/\1/' | head -n1`
  </code></pre>
  
  <p>but is it preferable to use pure perl in such cases? Here is the best I could come up with using perl. It is very cumbersome:</p>
  
  <pre><code>my $tmp;
  #want to find the planar study in current study
    foreach (glob "$DIR/image*.hd"){
      $tmp = $_;
      open FILE, "&lt;", "$_" or die $!;
      while (&lt;FILE&gt;)
        {
      if (/Image type:=4/){
        $tmp =~ s/.*image(\d+).hd/$1/;
      }
        }
      close FILE;
      last;
    }
   print "$tmp\n";
  </code></pre>
  
  <p>this also returns the desired output of 1. Is there a more effective way of doing this?</p>