while (<$tailf>) { chomp; my $line = $_; if($line =~ m/ on $ipaddress/) { if (scalar(@matches) <= 3){ push(@matches, $line); } } last; } foreach $line (@matches){ print "$line\n"; }