#!/usr/bin/perl -w use strict; my %seen = (); while () { my ($one, $two) = split; $seen{$one} = [$two, exists $seen{$one} ? @{$seen{$one}} : () ]; } for my $key (keys %seen) { print $key, " ", join(", ", @{$seen{$key}}), "\n"; } __DATA__ a 1 a 2 a 3 a 4 b 1 c 1 d 1