#takes first line from the and split values by ' ' into $lines and $matches ($lines, $matches) = split /\s/, ; #takes the next line from the , chop off the \n and split resulted string #into @a array by symbols $_ = ; $_ = $` if /$/; @a = split //, $_; #in this cycle(1) we create all possible combinations of substrings out of the #@a array, (out of the first line) and equals them to 1 for $i (0 .. $#a){ $e = $a[$i]; $hash{$e} = 1; for $y ($i+1 .. $#a){ $e .= $a[$y]; $hash{$e} = 1; } } #in this cycle(2) we read file line by line and for every line #we do exactly the same as the previous cycle but into #temporal hash and then in the foreach cycle(3) we increment #existed keys from the first hash if they are in the current line while(){ $_ = $` if /$/; @a = split //, $_; %thash = (); for $i (0 .. $#a){ $e = $a[$i]; $thash{$e} = 1 if defined $hash{$e}; for $y ($i+1 .. $#a){ $e .= $a[$y]; $thash{$e} = 1 if defined $hash{$e}; } } foreach $key (keys %hash){ $hash{$key}++ if defined $thash{$key}; } } #and finally here we go through the hash #and print only those keys which have their value == $matches $max = ''; foreach $key (keys %hash){ if($hash{$key} == $matches){ print "$key\n"; # $max = $key if length($max) < length($key); } } print "$max\n"; __DATA__ 3 2 strrringggg ssttrrringggg stttrrringgg