Take care with that code because your \b regular expression has a different idea about words then the \s one. For example, if you change the first data line to this:

This is a test-thingy from tester okay
then you'll get the following wierd output.
The word repeated in Line 1 and in column

This may or may not be a problem depending on your data.

To correct, you shouldn't use a separate condition to determine if the word occurs in a line and then search for the positions of the word in a different way, unless that's really necessary for performance reasons. That's code duplication and it's not surprising that it causes problems.

Here's an example of how you do the search only once.

my $word="test"; while(<DATA>) { my $occurs; @arr = split(/\s+/,$_); $col = ""; $i=0; foreach $k (@arr) { if($k eq "$word") { $col.=($i+1)."\t"; $occurs = 1; } $i++; } if ($occurs) { print "The word repeated in Line ".$.." and in column ".$col."\n"; } } __DATA__ This is a test-thingy from tester okay nothing message test center test test in proress ... test one test two

In reply to Re: Can anyone simplify this code by ambrus
in thread Can anyone simplify this code 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.