sdgaw erzswer
sdgaw erzswer

Reputation: 2382

Replacing array elements in Perl

I'm trying to replace an element in my array and my code doesn't seem to work.

my @wholeloop = (split //, $loop);

for my $i (0 .. $#wholeloop ) {
    if ( $wholeloop[$i] eq "i" ) {
        $wholeloop[$i] =~ htmlinsert($offset);
        $offset++
    }
}

I've read about problematics of doing stuff while iterating through an array, and maybe is there a better solution. I'm trying to replace specific occurences of a character in a string, and array seemed as a reasonable tool to use.

Upvotes: 1

Views: 9922

Answers (3)

Sobrique
Sobrique

Reputation: 53478

Typically - when iterating on a loop, you don't need to do it via:

for ( 0..$#array) {

Because

for ( @array ) { 

will do the same thing, but with an added advantage of $_ being an alias to the array variable.

for my $element ( @wholeloop ) {
    if ( $element eq "i" ) {
       $element = htmlinsert($offset++);
    }
}

$element is an alias so if you change it, you change the array. ($_ will do the same, but I dislike using it when I don't have to, because I think it make less clear code. This is a style/choice matter, rather than a technical one).

However for searching and replacing an element in a string – like you're doing – then you're probably better off using one of the other things perl does really well – regular expressions and pattern replacement. I can't give an example easily though, without knowing what htmlinsert returns.

Something like though:

 $loop =~ s/i/newvalue/g;

Will replace all instances of i with a new value.

Upvotes: 5

Rogue
Rogue

Reputation: 676

Perhaps you should use foreach. It is the most suitable for what you are trying to do here

my @array;  
foreach ( @array ) {  
    $_ =~ whatever your replacement is;  
}

Now, like Sobrique said, unless htmlinsert returns a RegEx value, that isn't going to work. Also, if you could give us context for "$offset", and what its purpose is, that would be really helpful.

Upvotes: 1

Becca Royal-Gordon
Becca Royal-Gordon

Reputation: 17861

=~ is Perl's "match regular expression" operator, so unless htmlinsert() returns a regex, it's probably not what you meant to do. You probably want to use =.

A more Perlish way to do this, though, might be to use the map function. map takes a block and an array and runs the block with each element of the array in $_, returning all the values returned by that block. For example:

my @wholeloop = map {
    $_ eq "i" ? htmlinsert($offset++) : $_;
} split //, $loop;

(The ? and : perform an "if/else" in a single line; they're borrowed from C. map is borrowed from functional programming languages.)

Upvotes: 2

Related Questions