Reputation: 10288
I would like to search for all instances and replace all separately, even if identical.
#!/usr/bin/perl
use strict;
use warnings;
my %dataThing;
my $x=0;
my $data = "1 - 2 - 2 - 4 - 7 - 343 - 3 - 1";
if( my @dataArray = ( $data =~ m/([0-9]+)/gis )){
foreach( @dataArray ) {
my $replace = "[thing-" . $x . "]";
# somehow replace $_ with above
...
# add to an array to store later
$dataThing{$replace} = $_;
$x++;
}
}
so output would be;
[thing-1] - [thing-2] - [thing-3] - [thing-4] - [thing-5] - [thing-6] - [thing-7] - [thing-8]
not
[thing-1] - [thing-2] - [thing-2] - [thing-3] - [thing-4] - [thing-5] - [thing-6] - [thing-1]
This would be possible in PHP by looping through the array and using str_replace with the function limit set to 1.
Upvotes: 2
Views: 347
Reputation: 20174
You can use the "e" modifier to the substitution operator to evaluate arbitrary code on the replacement side. This code can count the number of times it's been called and return that number.
my $data = "1 - 2 - 2 - 4 - 7 - 343 - 3 - 1";
my $x=0;
$data =~ s/([0-9]+)/"[thing-" . ++$x . "]"/ges;
Upvotes: 3