Pille
Pille

Reputation: 1

Merge and replace two array elements

How could I make it more simple?

@array= ('a','s','v','b','s','v','s','f','v');
$i= 0;
$maxarray= @array;
while ($i<$maxarray-1) {
    if (($array[$i] eq 's') && ($array[$i+1] eq 'v')) {
        splice (@array, $i, 1);
        $array[$i]= 'vs';
    } else { # if
        $i++;
    } # if
    $maxarray= @array;
} # while

output: (replace ('s', 'v') to ('vs')

Upvotes: 0

Views: 93

Answers (2)

Borodin
Borodin

Reputation: 126722

You could do this another way completely using a string substitution

@array = split ' ', "@array" =~ s/s v/vs/gr;

output

a vs b vs s f v

Upvotes: 1

choroba
choroba

Reputation: 241758

You can use splice to replace two elements in the middle of an array:

my $i = 0;
while ($i < $#array) {
    splice @array, $i, 2, 'vs'
        if 's' eq $array[$i] && 'v' eq $array[ $i + 1 ];
    $i++;
}

If you know the array can't contain a character (for example !) and that each element is just one character, you can join the array into a string and use the substitution to do the work:

my $str = join '!', @array;
$str =~ s/s!v/vs/g;
@array = split /!/, $str;

Upvotes: 3

Related Questions