http://www.perlmonks.org?node_id=1005172


in reply to Is it possible to get all tetra words with correct starting position using a better code within a loop?

I, too, thought of BrowserUk's  (?= (overlapping capture)) hack (Update: ColonelPanic previously used a version of this hack.) when I first read the OP, but supriyoch_2008 also wants starting positions. No problem, thought I, just throw in a little  (?{ code }) and the necessary info can be captured. (The offsets produced in the code examples below are 0-based rather than 1-based as supriyoch_2008 wants, but that's a mere detail. Also, I don't maintain that this approach is necessarily to be preferred as being faster/better/etc.)

However, a little fly in the soup. The code examples 'work', but I don't quite understand what's going on: the positions in the  @tetras_pos array are doubled for some reason, hence the  $_ * 2 indexing hack in printing position info. In the second example, I can understand the presence of the (5, 6, 7, 8) positions at the end of the (0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8) list of positions as resulting from failed attempts by  (?= (....)) to match in positions in which a match is impossible because there are fewer than four characters remaining in the string, but I still don't understand the doubling in the previous part of the list.

I have the feeling this behavior has been touched on before somewhere, but I can't lay my hands on a reference. Can anyone offer any insight?

>perl -wMstrict -le "my $pro = 'ABCDEFGH'; ;; my @tetras_pos; my @tetras = $pro =~ m{ (?= (....) (?{ push @tetras_pos, $-[1] })) }xmsg; ;; print qq{'$tetras[$_]' @ $tetras_pos[$_ * 2]} for 0 .. $#tetras; print qq{@tetras_pos}; ;; @tetras_pos = (); @tetras = $pro =~ m{ (?= ((?{ push @tetras_pos, pos $pro }) ....)) }xmsg; ;; print qq{'$tetras[$_]' @ $tetras_pos[$_ * 2]} for 0 .. $#tetras; print qq{@tetras_pos}; " 'ABCD' @ 0 'BCDE' @ 1 'CDEF' @ 2 'DEFG' @ 3 'EFGH' @ 4 0 0 1 1 2 2 3 3 4 4 'ABCD' @ 0 'BCDE' @ 1 'CDEF' @ 2 'DEFG' @ 3 'EFGH' @ 4 0 0 1 1 2 2 3 3 4 4 5 6 7 8

Replies are listed 'Best First'.
Re^2: Is it possible to get all tetra words with correct starting position using a better code within a loop?
by supriyoch_2008 (Monk) on Dec 03, 2012 at 06:28 UTC

    AnomalousMonk

    Thank you very much for the code. It has solved my problem. I am sorry for late reply as I had no access to internet for a few days due to some technical problem.

    With Regards,