Backtracking is something internal, and to mess with that, you ugly hacks. It would probably involve a new implementation of the regex engine to do what you want with backtracking.
To add the digits, you need to evaluate some code. With (??{}) it is almost impossible to evaluate and rematch, because when you try recursion, you can't easily use $1 over and over, because it'll be $2 (if you have a single set of parentheses) the second time. And you can't even use $1 within its own parentheses. Forget recursive regexes for now.
As I said, you need to evaluate some code, and you could try doing that with /e, and wrapping it in a loop. However, it's still nasty and there are better ways to do it.
Mathematics may be the answer to this problem. If you have a number, and add all digits and repeat until you have a single digits left, you're going through a lot of trouble to implement $digit = $number % 9 || 9 (figure out how that works yourself).
Illustation:
#!/usr/bin/perl -w use strict; sub sum { my $sum = 0; $sum += $_ for @_; return $sum; } for (1..10) { my $copy = my $number = int rand 1e4; print "=== Test: $_ - Number: $number ===\n"; print "Brute force:\n"; while ($copy > 9) { my @digits = split //, $copy; $copy = sum(@digits); print "\t", join(' + ', @digits), " = $copy\n"; } print "Maths:\n"; print "\t$number % 9 || 9 = ", $number % 9 || 9, "\n\n"; }
There is a minor problem: 0 % 9 || 9 is of course 9, and you want 0. A simple && can fix it, I'll leave its placement to you.=== Test: 1 - Number: 5943 === Brute force: 5 + 9 + 4 + 3 = 21 2 + 1 = 3 Maths: 5943 % 9 || 9 = 3 === Test: 2 - Number: 3630 === Brute force: 3 + 6 + 3 + 0 = 12 1 + 2 = 3 Maths: 3630 % 9 || 9 = 3 === Test: 3 - Number: 3309 === Brute force: 3 + 3 + 0 + 9 = 15 1 + 5 = 6 Maths: 3309 % 9 || 9 = 6 === Test: 4 - Number: 8085 === Brute force: 8 + 0 + 8 + 5 = 21 2 + 1 = 3 Maths: 8085 % 9 || 9 = 3 === Test: 5 - Number: 117 === Brute force: 1 + 1 + 7 = 9 Maths: 117 % 9 || 9 = 9 === Test: 6 - Number: 8474 === Brute force: 8 + 4 + 7 + 4 = 23 2 + 3 = 5 Maths: 8474 % 9 || 9 = 5 === Test: 7 - Number: 8132 === Brute force: 8 + 1 + 3 + 2 = 14 1 + 4 = 5 Maths: 8132 % 9 || 9 = 5 === Test: 8 - Number: 1518 === Brute force: 1 + 5 + 1 + 8 = 15 1 + 5 = 6 Maths: 1518 % 9 || 9 = 6 === Test: 9 - Number: 6491 === Brute force: 6 + 4 + 9 + 1 = 20 2 + 0 = 2 Maths: 6491 % 9 || 9 = 2 === Test: 10 - Number: 2170 === Brute force: 2 + 1 + 7 + 0 = 10 1 + 0 = 1 Maths: 2170 % 9 || 9 = 1
U28geW91IGNhbiBhbGwgcm90MTMgY
W5kIHBhY2soKS4gQnV0IGRvIHlvdS
ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
geW91IHNlZSBpdD8gIC0tIEp1ZXJk
In reply to Re: Requiring backtracking a certain number of times
by Juerd
in thread Requiring backtracking a certain number of times
by dragonchild
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |