sub score{ my($str, $array) = @_; # ensure that longer string comes before its prefix my @substring = sort { $b cmp $a } @$array; my $re = join '|', map "(?=($_))", @substring; my($count, $next) = (0, 0); while ($str =~ /$re/g) { # $-[0] is the position at which we matched # @- describes the matched captures, so $#- is the actual capture matched my($start, $which) = ($-[0], $#- - 1); my $end = $start + length($substring[$which]); $next = $start if $next < $start; next if $end < $next; $count += $end - $next; $next = $end; } return $count; }