I have a need for a substr() like function that works on words, rather than characters; for purposes of this discussion, we'll assume a word is a sequence of non-whitespace characters separated by whitespace.

Tilly gave me a code snippet which I have hacked into the following:

if ($window_start > 0) { $text_body =~ /\S+/g foreach 1..$window_start; $start_index = pos($text_body); } else { $start_index = 0; } $text_body =~ /\S+/g foreach 1..$window_size; $end_index = pos($text_body); $windowed_text = substr($text_body, $start_index, ($end_index - $start +_index));

Here's my problem: The first match works perfectly. $start_index gets set appropriately for the $window_start'th word. The second match doesn't work at all. Even if $window_start is 0, and this the second match is the only match.

All I can think is that either I don't understand something, or I'm seeing what I know I wrote rather than what I wrote -- but I've tried to rule out the latter.


In reply to Slicing a string on words by dstar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.