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