#!perl use strict; use warnings; my @array1 = qw(read eat book apple play football novel); my @array2 = qw(book apple novel banana football tennis magazine); # The follows relationship my %follow; @follow{@array1} = @array2; # Keeping track of what followers I have already used my %h2 = map {$_=>1} @array2; # Start with things that are not followers my @out = ([grep !exists $h2{$_}, @array1]); # Put followers of the previous column on as a new column while (%h2) { push @out, [@follow{@{$out[-1]}}]; delete @h2{@{$out[-1]}}; } use Data::Dumper; print Dumper(\@out); END { use Data::Dumper; print Dumper(\@out); }