$ perl change.pl E=((?:1111111111)*)((?:111111)*)((?:11111)*)((?:1)*) Trying to change 12 with 10 6 5 1... ((?:1111111111)*)((?:111111)*)((?:11111)*)((?:1)*) on 111111111111 Code doesn't get run after once. 12: 3 is better than 0 Matched! C=3 12: Trying to change 14 with 10 6 5 1... ((?:1111111111)*)((?:111111)*)((?:11111)*)((?:1)*) on 11111111111111 Code doesn't get run after once. Matched! No matching combination found 14: Trying to change 36 with 10 6 5 1... ((?:1111111111)*)((?:111111)*)((?:11111)*)((?:1)*) on 111111111111111111111111111111111111 Code doesn't get run after once. Matched! No matching combination found 36: $