# ... while () { my ($id, $string) = (split /[,\s]+/)[0,1]; my $cur_len = length $string; next if defined $results{$id} and $cur_len > $results{$id}{len}; $results{$id} = { str => $string, len => $cur_len }; } say "$_ $results{$_}{str}" for sort keys %results; #...