use re 'eval';
sub min_chunks {
  my ($word1, $word2) = @_;
  my $str = lc "$word1:$word2";
  for my $c (1..length $_[0]) {
    my $capture = "(\\w+)" x $c;
    $capture = qr/^$capture:/;
    my @backrefs;
    if (my @arr = $str =~ /$capture(??{
      no strict 'refs';
      @backrefs = build_str($word2, [ map $$_, 1..$c ], 1..$c);
      @backrefs ? '' : '$';
    })/)
    {
      # See the word divisions! Uncomment the code!
      # no strict 'refs';
      # print join("/", @arr), " ", join("/", map $$_, @backrefs), "\n";
      return $c;
    }
  }
}

# See if we can build the word from a set of substrings
sub build_str {
  my ($word, $substr, @order) = @_;
  for my $i (0..$#order) {
    my $len = length $$substr[$i];
    if (substr($word, 0, $len) eq $$substr[$i]) {
      return "$order[$i]" if $len >= length $word;
      my $new_word = substr($word, $len);
      my @new_substr = @$substr;
      splice(@new_substr, $i, 1);
      my @new_order = @order;
      splice(@new_order, $i, 1);
      if (my @new_build = build_str($new_word, \@new_substr, @new_order)) {
        return "$order[$i]", @new_build;
      }
    }
  }
  return;
}
