my %hash; while ( <> ) { my ( $dept, $email ) = split /:/; $hash{ $dept } .= "$email,"; } s/,\z// for values %hash;