my %data; while () { chomp($_); my ($first, $second) = split(/\s+/, $_); push(@{$data{$first}}, $second); } foreach my $first (sort {$a <=> $b} keys %data) { print "$first ", join('-', @{$data{$first}}), "\n"; }