-3

I have a text file with three occurrences of the string 'object'.

There is an object on the table
The object is under the chair
There might be an object in my pocket

I want to write a Perl script to replace every occurrence of 'object' with another string contained in an array of three elements. The first element of the array is matched to the first occurrence of 'object', the second element to the second occurrence, and so on.

For example, if

my @pattern = ( "apple", "mango", "orange" );

Then the output must be:

There is an apple on the table
The mango is under the chair
There might be an orange in my pocket
Borodin
  • 126,100
  • 9
  • 70
  • 144

1 Answers1

4

There's a useful feature of perl, that is /e flag to regex, that says 'evaluate an expression.

So you can do it like this:

#!/usr/bin/env perl
use strict;
use warnings; 

my @pattern = ( "apple","mango","orange" );

while ( <DATA> ) {
   s/object/shift @pattern/eg; 
   print ;
}

__DATA__
There is an object on the table
The object is under the chair
There might be an object in my pocket

Although note that because you're shifting @pattern it'll empty out as you go. (the 4th replacement will be 'undefined').

But you can do something similar if you're looking to do a rotating pattern.

#!/usr/bin/env perl
use strict;
use warnings; 

my @pattern = ( "apple","mango","orange" );
my $hit_count = 0; 

while ( <> ) {
   s/object/$pattern[$hit_count++ % @pattern]/eg; 
   print ;
}

This keeps a running total of how many times the pattern has matched, and uses the modulo operator to select the right array element, so future hits get replaced in rotating order.

Sobrique
  • 52,974
  • 7
  • 60
  • 101