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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.