selenocysteine
selenocysteine

Reputation: 202

Perl: quick replacing of occurrences of multiple words in an array

Sorry if it is a duplicate topic, but I've searched inside the forum and I've only found similar but not identical questions.

My problem is:

I've got an array of strings like this one:

@array = ("My name is "Annie" \n", "My mother's name was "Annie", too. \n", "I am "27" years old \n", "I live in "Minnesota" \n");

And another array of strings like this one:

@subs = ("Annie", "22", "Minnesota");

I would like to:

1) find any occurrence of the words from the second array in the first array (for instance: Annie would match with the first and the second element, Minnesota only with the last one).

2) substitute all the words which matched with any element of the second array with the same word followed by "-DATA" (for instance: "My name is "Annie-DATA"\n").

I guess that this could be easily done with one or two for loops, but I'm wondering if there's any quicker way, maybe with some smart use of PERL's regexs.

Thank you!

Upvotes: 3

Views: 1072

Answers (3)

Qtax
Qtax

Reputation: 33908

Another solution which also escapes meta chars:

# escape possible meta characters and join
my $sub = join '|', map { quotemeta } @subs;

# replace in the array
s/($sub)/$1-DATA/g for @array;

If you don't want to change the values directly in @array use map instead of for. Eg: my @new = map s/($sub)/$1-DATA/g, @array;

Upvotes: 1

imran
imran

Reputation: 1560

One solution:

use strict;
use warnings;
my @array = ("My name is \"Annie\" \n",
   "My mother's name was \"Annie\", too. \n",
   "I am \"27\" years old \n",
   "I live in \"Minnesota\" \n");
my @subs = ("Annie", "22", "Minnesota");

my @new_array = map { my $line = $_; 
                      $line =~ s/$_/$_-DATA/g foreach @subs; 
                      $line } @array;

Upvotes: 2

alestanis
alestanis

Reputation: 21863

You could replace like this:

s/(Annie|22|Minnesota)/\1-DATA/g

Upvotes: 2

Related Questions