my $str = "discard\ndiscard\nkeep1\nkeep2"; my $index = 2; my @arr = grep {$index-- <= 0} split "\n", $str;