in reply to Re: Replace multiple strings in a string
in thread Replace multiple strings in a string

"faster" in this sort of context, even if true, is altogether irrelevant as any difference would be completely swamped by the time taken for the body of the loop. However the difference between:

for (;$i<$#Search+1;$i++) {

(which implies a continuation of a previous loop because of the missing $i initialisation btw) and

for my $i (0 .. $#Search) {

which is clear and succinct is absolutely compelling. Note in particular (you may have missed it because of the lack of white space) the hoop the C style for loop goes through to get the range correct? In the Perl style loop there are no hoops so the interpretation by the code author, the code maintainer and the Perl interpreter all align perfectly so the chance of the iteration range being wrong is pretty close to 0.

Clarity and thus maintainability is the key reason for preferring the Perl style loop almost always.

Perl is the programming world's equivalent of English

Replies are listed 'Best First'.
Re^3: Replace multiple strings in a string
by Laurent_R (Canon) on May 08, 2014 at 11:36 UTC
    Clarity and thus maintainability is the key reason for preferring the Perl style loop almost always.

    ++. I absolutely agree. I mentioned speed only as side effect and heavily qualified the claim that it is faster ("probably somewhat faster"). I agree that speed is probably not really relevant, let's say that it is good enough to know at least that it is not slower. Clarity is the most important reason, and although TIMTOWTDI, I am almost always using the Perl-style for loop for that reason (and also avoiding to use the $i array index when possible).

    Update: I just saw your other post below suggesting the use of a hash or an array of arrays (or array of hashes or similar data structures) and thus getting rid of the need to use array subscripts, I was actually also thinking of something similar, and I agree that this is a much better solution. The idea of walking through two arrays in parallel relying on a common index is at best clumsy, in view of the efficient data structures (in terms of coding simplicity) offered by Perl.