I share the suspicions of and disdain for homework not labeled as such expressed by others, but since several code contributions have already been made, here's mine.

As noted above, the tricky part is defining the word regex. This should also probably be defined separately and passed to the emphasize() function rather than being hard-coded.

perl -wMstrict -le "{ my %emphasis; my $word = qr{ (\b \w+ \b) }xms; sub emphasize { my $string = shift; %emphasis = map { $_ => 0 } @_; my $intro = qq{@{[ sort { $a <=> $b } keys %emphasis ]}}; my $words = 0; $string =~ s{ ($word) } { exists $emphasis{++$words} ? qq{**$1**} : $1 }xmsge; return qq{$intro $string}; } } my $string = 'Sam goes to school to play football.'; print emphasize($string, 4, 7); print emphasize($string, 7, 2, 4); print emphasize($string); print emphasize('the cow jumped over the', 3, 4, 1); " 4 7 Sam goes to **school** to play **football**. 2 4 7 Sam **goes** to **school** to play **football**. Sam goes to school to play football. 1 3 4 **the** cow **jumped** **over** the

In reply to Re^2: character offset to word offset by AnomalousMonk
in thread character offset to word offset by newbio

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.