in reply to regexp help -- word boundaries

I believe what you're trying to do is replace words without also replacing words which contain the original words. Or to put it another way, you want each word bracketed by word boundaries.

Thankfully for you, there's an easy way to specify this: \b

my $x = 'a'; my $y = 'b'; while (<DATA>) { chomp; s/\b$x\b/$y/g; print "$_\n"; } __DATA__ a a a a
Incidently, use of $a and $b is not recommended, since these are used in sorts.

Replies are listed 'Best First'.
Re^2: regexp help -- word boundaries
by japhy (Canon) on Jul 11, 2005 at 12:07 UTC
    But you can't be sure that $x starts and ends with an alphanumeric character, in which case \b$x\b wouldn't match when $x is surrounded by spaces.

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart