hdb => sub { my $input = shift; my $length = length $$input; my $i = 0; while( $i < $length ) { # redundant, but to be on the safe side $i++; # length of next candidate my $possible = substr $$input, 0, $i; # next candidate my $j = index $$input, $possible, $i; # try to find it to the right if( $j > 0 ) { # if found, skip ahead $possible = substr $$input, 0, $j; # the candidate has to be this long at least $i = $j; # store its length } # check if we have a solution already if( substr( $$input, $i ) eq substr($$input, 0, $length - $i) ) { return $possible; # success ! } } # will never reach here return ''; },