my ($output, @lines) = ''; my ($num, $re, $file) = @whatever; open my $fh, '<', $file or die $!; while (<$fh>) { push @lines, $_; shift @lines if @lines > $num; # $output = join('', @lines), last if /$re/; $output = $lines[0], last if /$re/; } close $fh or die $!;