in reply to Detecting position of a substring within a string

One possible solution is to check @- and @+:

use warnings; use strict; sub calcit { my $in = shift; my %rules = (A => 1,B => 1,C => 0,D => 1); my ($s,$s1,$s2) = (0)x3; while ($in=~/(\d+)([ABCD])/g) { my ($n,$op) = ($1,$2); $s += $n * $rules{$op}; $s1 += $n * $rules{$op} unless $op eq 'D' && $-[0]>0; $s2 += $n * $rules{$op} unless $op eq 'D' && $+[0]<length($in); } return ($s,$s1,$s2); } use Test::More; is_deeply [calcit("2D40A2C1B4D")], [47,43,45], "2D40A2C1B4D"; is_deeply [calcit("2D40A2C1B")], [43,43,41], "2D40A2C1B"; done_testing;

But TIMTOWTDI, for example you could ignore all "D" codes in the initial processing of the string and then use a separate regex (/^(\d+)D/ resp. /(\d+)D$/) to account for them.

Replies are listed 'Best First'.
Re^2: Detecting position of a substring within a string
by K_Edw (Beadle) on Mar 24, 2016 at 09:25 UTC
    Thank you! I've managed to successfully modify this to fit into my script and the desired result is met.