{ my @cache; # a cache of substring-finding subs sub substrings { my $string = shift; my $length = length $string; # use cached sub if we have one return $cache[$length]->($string) if exists $cache[$length]; # create sub to find substrings for this length my $sub = 'sub { $_ = shift; return ('; foreach my $length (1..length($string)) { foreach my $offset (0..length($string)-$length) { $sub .= "substr(\$_,$offset,$length),"; } } $sub .= ")};"; $cache[$length] = eval $sub; # and use it return $cache[$length]->($string); } }