I have the following string :
Cat dog fox catepillar bear foxy
I need to replace "cat" and "fox" words from this sentence to word "animal"
I do the following:
$Str1="cat";
$Str2="fox";
$NewStr="animal";
open(F1, "<$inputFile") or die "Error: $!";
open(F2, ">$outputFile") or die "Error: $!";
while ($line = <F1>) {
$line =~ s/$Str1|$Str2/NewStr/g;
print F2 "$line";
}
But the problem that word's "catepillar" and "foxy" parts("cat" and fox) also are replaced.
How to replace only words "cat" and "fox"?
There's a couple more problems here.
# First, always use strict and warnings
# This will save you tons
use warnings;
use strict;
# declare your vars with 'my' for lexical scope
my $inputFile = "somefile";
my $outputFile = "someotherfile";
my $Str1="cat";
my $Str2="fox";
my $NewStr="animal";
# use 3-arg lexically scoped open
open(my $F1, "<", $inputFile) or die "Error: $!";
open(my $F2, ">", $outputFile) or die "Error: $!";
while (my $line = <$F1>) {
# surround with word boundary '\b'
# NewStr is missing the "$"
$line =~ s/\b(?:$Str1|$Str2)\b/$NewStr/g;
# UPDATED
# this should work to remove the parens
$line =~ s/(\($NewStr\))/$NewStr/g;
print $F2 "$line";
}
# close your file handles
close $F1;
close $F2;
$line =~ s/\b(?:$Str1|$Str2)\b/$NewStr/g;
What the changes mean:
\b
zero width assertion for a word boundary
(?:
start a group but don't use it for capturing, just grouping
Use a word boundary assertion to build your regex. You can find information on it at http://perldoc.perl.org/perlre.html.