index -> regex -> split
use strict; my $word = 'and'; while (<DATA>) { if (index($_, $word) > -1) { while (m/(?:^|[^a-zA-Z'])$word[^a-zA-Z']/gi) { print "The word\n$word\noccured in line " . ($.-1) . " as +the " . ends(scalar(split(/[^a-zA-Z']+/, substr($_, 0, pos($_) - 1 +)))) . " word.\n\n"; } } } BEGIN { my @ends = ('','st','nd','rd'); sub ends { return $_[0] . @ends[$_[0] % 10] if $_[0] % 10 < 4 && $_[0] % +10 > 0 && int($_[0] / 10) != 1; return $_[0] . 'th'; } } __DATA__ Four score and seven years ago our fathers brought forth, upon this co +ntinent, a new nation, conceived in liberty, and dedicated to the proposition tha +t "all men are created equal" Now we are engaged in a great civil war, testing whether that nation, +or any nation so conceived, and so dedicated, can long endure. We are met on +a great battle field of that war. We have come to dedicate a portion of it, as + a final resting place for those who died here, that the nation might live. Thi +s we may, in all propriety do. But, in a larger sense, we can not dedicate -- we + can not consecrate -- we can not hallow, this ground -- The brave men, living +and dead, who struggled here, have hallowed it, far above our poor power to add +or detract. The world will little note, nor long remember what we say here; while +it can never forget what they did here.

In reply to Re: tracking words in lines by TedPride
in thread tracking words in lines by Anonymous Monk

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.