in reply to Re: Regexp to extract groups of numbers
in thread Regexp to extract groups of numbers

I would not use substr, but if I were, I wouldn't use a while loop like you did - but I'd use a for:
for (my($i, $s) = (0, 3); $i < length($pie); $i += $s) { print substr($pie, $i, $s), "\n"; }

Replies are listed 'Best First'.
Re^3: Regexp to extract groups of numbers
by demerphq (Chancellor) on Feb 07, 2005 at 11:36 UTC

    Except that three arg for loops are just while loops in disguise. :-)

    Pretty much anyway.

    ---
    demerphq

      And while loops are just gotos in disguise. Pretty much anyway.

      However, the for() loop has a couple of points in favour over the while loop:

      • It doesn't "leak" loop-variables. The scope of the $index/$i variable is limited to the loop, unlike the while, where the scope of $index extends to the surrounding block.
      • All statements needed for the loop control - initialization of the variant, the condition, and the increment of the variant are all together. On one line even. At the while, the initialization of the variant is outside the while, then we have the condition, and somewhere in the block, we have the increment of the variant.
      Reason enough for me to pick a for loop over a while in this case.

        And while loops are just gotos in disguise. Pretty much anyway.

        While i posted somewhat tongue-in-cheek im curious: Is that really true in perl?

        and somewhere in the block, we have the increment of the variant.

        I suppose you could code it that way, but you can also use a continue block:

        while (EXPR) { } continue { STMTS; }

        Which can be useful at times and is pretty much what Perl does anyway. Ie:

        for(INIT;EXPR;INCR) { STMTS; }

        more or less becomes:

        { INIT; while (EXPR) { STMTS; } continue { INCR; } }

        I think how much value you place on your second point will vary depending on your exposure to C and other C like languages. Personally I always hated 3 arg for loops finding them difficult to read, but lately ive been doing a lot of C and have come to appreciate them a lot more (probably becuase I find reading them not to be so confusing as it used to be).

        Anyway, i stuck the smiley face on there for a reason. I just thought the fact that the two constructs are identical in perl (insofar as perl converts 3arg for loops into while continue constructs anyway) made your comment a touch ironic. :-)

        ---
        demerphq