@array1 = [A,B,F,G] @array2 = [A, B, C, D, E, F, G] #### my @filtered; @paths = sort { @$a <=> @$b } @paths; LINE: for ( my $i = 0; $i < scalar @paths; $i++ ) { my $path = $paths[$i]; my %nodes; @nodes{@$path} = (); for ( my $j = $i + 1; $j < scalar @paths; $j++ ) { my $path_b = $paths[$j]; my $c = grep { exists $nodes{$_} } @$path_b; next LINE if $c == scalar @$path; } push @filtered, $path; }