my @lines = ...; # Ausgagsliste my %hits; foreach my $l (@lines) { $l =~ m/#(\w+)\.xml/; push @{$hits{$1}},$l; # Hash land ->[line1,line2...] }; my @result; foreach my $k (keys %hits) { if (@{$hits{$k}} > 2) { push @result,@{$hits{$k}}[-2,-1]; # letzte 2 Einträge } else { push @result,@{$hits{$k}} # alle Einträge für land } };