# some sample data: my @rep1_pids = (1..10); my @rep2_pids = (11..20); my @rep3_pids = (21..30); my @pairs = ( "11\t5", "22\t14", "4\t8", "1\t29" ); # organize sources into HoH (%arrayhash): # create %hashbuilder first, to assign source names to arrays my %hashbuilder = ( rep1 => \@rep1_pids, rep2 => \@rep2_pids, rep3 => \@rep3_pids, ); # for each source, array names will be the primary hash keys, # and the array values will become keys of the secondary hashes: my %arrayhash; for my $src ( keys %hashbuilder ) { $arrayhash{$src}{$_} = 1 for ( @{$hashbuilder{$src}} ); } # now identify sources for the members (items) in each pair: for my $pairstr ( @pairs ) { my $srcs = ''; for my $item ( split( /\t/, $pairstr )) { for my $src ( sort keys %arrayhash ) { if ( $arrayhash{$src}{$item} ) { $srcs .= "$item is from $src; "; } } } print $srcs, "\n"; }