Jack Perl
Jack Perl

Reputation: 15

Replacing many words in brackets with a new one

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"

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;
     print $F2 "$line";

}

# close your file handles
close $F1;
close $F2;

it is ok , but But if I have some words in brackets"()". Let's say I have "word fox like this (fox). I have the result - "(animal)" with brackets. How to remove brackets when I replace word?

Upvotes: 0

Views: 78

Answers (2)

amalgamate
amalgamate

Reputation: 2310

@tripleee is correct. Just making it super easy:

$line =~ s/\(?\b(?:$Str1|$Str2)\b\)?/$NewStr/g;

Note that with this and your code posted above Cat will not get selected because of capitalization.

Upvotes: 0

tripleee
tripleee

Reputation: 189397

s/\(?\b(?:cat|fox)\b\)?/animal/g;

Upvotes: 4

Related Questions