$ cat lists_2.pl #!/usr/bin/perl use strict; use warnings; use 5.10.0; # Build a few lists my @lists; for my $i (0 .. 1+int(3*rand)) { # several lists to compare push @{$lists[$i]}, int 16 * rand for 1 .. 15; print "LIST $i: ", join(", ", @{$lists[$i]}), "\n"; } # Track the items found in each list, including the order in # which they appear my %tally; for my $listnum (0 .. $#lists) { # Get a list my $list=$lists[$listnum]; for my $itemnum (0 .. $#$list) { # Get next item from the list my $item = $$list[$itemnum]; # Each item slot (value in list) gets an array, # where each slot is associated with a list. # In that array is an array of indexes into the # list where each item is found push @{$tally{$item}[$listnum]}, $itemnum; } } # Show which items were in all lists my $numlists = @lists; my $all = (1<<$numlists)-1; print "\nThere were $numlists lists.\n\n"; for my $item (sort {$a<=>$b} keys %tally) { if ($numlists == grep { $_ } @{$tally{$item}}) { print "Item $item in all lists:"; for my $idxlist (0 .. $#lists) { print " list $idxlist: ", join(", ", @{$tally{$item}[$idxlist]}), "\n"; } print "\n"; } $ perl lists_2.pl LIST 0: 5, 6, 9, 13, 3, 0, 1, 2, 5, 5, 10, 14, 15, 8, 4 LIST 1: 11, 5, 2, 12, 3, 4, 9, 13, 14, 14, 9, 15, 5, 2, 6 LIST 2: 6, 0, 7, 12, 11, 2, 13, 8, 14, 8, 13, 5, 0, 1, 7 LIST 3: 3, 14, 14, 11, 7, 10, 12, 8, 6, 15, 5, 6, 14, 6, 11 There were 4 lists. Item 5 in all lists: list 0: 0, 8, 9 list 1: 1, 12 list 2: 11 list 3: 10 Item 6 in all lists: list 0: 1 list 1: 14 list 2: 0 list 3: 8, 11, 13 Item 14 in all lists: list 0: 11 list 1: 8, 9 list 2: 8 list 3: 1, 2, 12