my %routes; while (my $line = <>) { # Grab the route my ($key) = ($line =~ /^(\S+)\s/); # Make sure we have an array ref for this key $route{$key} ||= []; # And add this line push @{$route{$key}}, $line; } foreach my $value (values %routes) { if (@$values > 1) { print @$values; print "\n"; } }