#!/usr/bin/perl -s
# spongegrep - print input if regexp matches anywhere
# flags: -i case insensitive, -v negate

my @seen = ();
my $rx = shift || die "Usage: spongegrep [-i] [-v] REGEXP\n";

if ($i) {
  $rx = "(?i)$rx";
}

m/$rx/;  # fail early on faulty regexps

while (<>) {
  push @seen, $_;
  if (/$rx/) {
    exit 1  if $v;
    print @seen;
    while (<>) {
      print;
    }
    exit 0;
  }
}

if ($v) {
  print @seen;
  exit 0;
} else {
  exit 1;
}