in reply to Re^2: How to count substitutions on an array
in thread How to count substitutions on an array

foreach $line (@array) {
     $count += s/\b$oldline\b/$spliced/eg for @array;
     # ... more code here
}

Another point to consider with this block of code is that the
    $count += s/\b$oldline\b/$spliced/eg for @array;
statement is executed for each and every element of the
    foreach $line (@array) { ... }
loop, but unless something tricky is going on in the  # ... more code here section, every execution of
    $count += s/.../.../eg for @array;
after the first will have nothing to do: every substitution will have already been made on the first execution, i.e., with the processing of the very first element of the outer loop.


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^4: How to count substitutions on an array
by Anonymous Monk on Aug 13, 2016 at 19:11 UTC

    You have pointed out well that I drafted that sample code too quickly. I have used similar code in other projects, but in this project I had in mind to do the substitution for the entire array…and that caused the Freudian? slip with that. I did not mean to structure the nested loop to act on the entire array with each substitution. It should have looked more like:

    @array = @array2; @array2 = (); foreach $line (@array) { $count = $line =~ s/\b$oldline\b/$spliced/eg; $totalcount += $count; push @array2, $line; }

    I had assumed that the variable on the replacement side would need to be evaluated, but it appears you are correct and the "e" is unnecessary. Removing that has sped up the script by about 3%. I learned something. Thank you!