Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a test file (text.txt) with following lines.
<String> <This is the firstline> <This is the secondline>
What I want to do is to do a find the exact match & replace.
open (FH,"text.txt"); @lines=<FH>; @patterns = qw/<string> line secondline/; @replace = qw/'<REPLACED>' 'line_R' 'secondline_R'/; foreach $line (@lines){ chomp $line; for ($i=0;$i<=2;$i++){ if ($line =~ /\B$patterns[$i]\B/i){ $line =~ s/$patterns[$i]/$replace[$i]/i; push @repd,$line; } } } foreach $line (@repd){ print "$line\n"; }
My desired output.
'<REPLACED>' //<String>->'<REPLACED>' <This is the 'secondline_R'> // secondline->'secondline_R'
But what i am getting as output
With RegExp '/\B$patterns$i\B/i'

'<REPLACED>' //Match only non-word char boundary.

With RegExp "/\b$patterns$i\b/i"

<This is the 'secondline_R'> //failed to match non-word chars '<,>'.


Can anybody help fixing my REGEXP to exactly match word & non-word chars?
Thanks,

Replies are listed 'Best First'.
Re: word & non-word boundries
by almut (Canon) on Mar 03, 2010 at 11:27 UTC

    Why don't you put the \b / \B in the patterns spec?

    @patterns = qw/\B<string>\B \bline\b \bsecondline\b/; ... if ($line =~ /$patterns[$i]/i){ $line =~ s/$patterns[$i]/$replace[$i]/i;