#! perl -slw use strict; use Data::Dump qw[ pp ]; my @array = ("11 12","11 13", "9 8 7", "3 4", "11 4 111") ; ## combine AGAIN: for my $i ( 0 .. $#array ) { for my $j ( $i+1 .. $#array ) { for my $n (split ' ', $array[ $j ]){ if( $array[ $i ] =~ m[\b$n\b] ) { $array[ $i ] .= ' ' . splice @array, $j, 1; redo AGAIN; } } } } ## dedup for ( @array ) { 1 while s[(\b\d+)\s(?=.*\b\1\b)][]g; } pp \@array;