# ================================================================= fortgrep.pl
#  PERL Script to display fortunes containing the regexp passed in.
#
#  Usage: fortgrep regexp [files...]
#
#  - Kevin Grover, grover@isri.unlv.edu
#  Sat 06 Mar 1993  - Created
# =============================================================================

$regexp = shift @ARGV || die "Usage: fortgrep regexp [files...]\n";
$sep = "%";
$needsep = 0;

if (@ARGV) {
  file: while ($f = shift @ARGV) {
    if (!open(IN, "<$f")) {
      warn "Can't open input file $f: $!\n";
      next file;
    }
    &process;
    close(IN);
  }
} else {
  *IN = *STDIN;
  &process;
}

sub process {
  $match = 0;
  @fort = ();
  while (<IN>) {
    if (m/^$sep/o) {
      if ($match) {
         $match = 0;
         print "$sep\n" if $needsep;
         $needsep = 1;
         print @fort;
      }
      @fort = ();
    } else {
      push (@fort,$_);
      $match = 1 if (m/$regexp/o);
    }
  }

  # Handle last match on fortune before EOF

  if ($match && @fort) {
    print "$sep\n" if $needsep;
    $needsep = 1;
    print @fort;
  }
}
