my @lines; while (<>) { push @lines, $_; shift @lines if @lines > 3; } if ($lines[2] =~ $regex1) { if ($lines[1] =~ $regex2) { if ($lines[0] =~ $regex3) { # Do your work here. } } }