tags:

views:

102

answers:

1

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.

+3  A: 

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;
Andrew Medico
Thanks, are you able to explain a little bit more in plain what the "e" modifier does?
Phil Jackson
It means that the code on the right-hand side of the substitution operator is evaluated as a full-fledged Perl expression and the result of the evaluation is used as the replacement text, instead of simply as an interpolated string.
Andrew Medico
Thank you, very helpful.
Phil Jackson