in reply to Regexp to extract groups of numbers

my $pie = 123456789; my @pies = ($pie =~ /(\d{3})/g); print join("\n", @pies);
However, I would prefer to use the substr() function thus:
$pie = 123456789; my $index = 0; while($index < length($pie)) { print substr($pie, $index, 3)."\n"; $index += 3; }
I choose substr() over unpack() because pack() and unpack() make my brane hurt.

Replies are listed 'Best First'.
Re^2: Regexp to extract groups of numbers
by Anonymous Monk on Feb 07, 2005 at 11:21 UTC
    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"; }

      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.