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:
then you'll get the following wierd output.This is a test-thingy from tester okay
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |