my %IDs; # when reading the ID file, for each line do something like $IDs{$current_id} = []; # and then for each line in the four other files: while (my $line = <$file>) { my ($id, $value) = split / /, $line; push @{$IDs{$id}}, $value } # and at the very end, print them all out: for my $id (sort keys %IDs) { print "$id: ", join(', ', @{$IDs{$id}}), "\n"; }