[Israel.pm] C style for loop

Gabor Szabo gabor at szabgab.com
Thu Mar 8 22:41:48 PST 2012


use strict;
use warnings;
use v5.10;

my $i = 0;
for ($i=0; $i <= 9; $i++) {
  #say $i;
}
say $i;  # 10

my $j = 0;
for $j (0..9) {
  # say $j;
}
say $j; # 0

In the c-style for loop we kept the value *that failed the condition*
but I don't think these cases are very interesting.

Maybe something like this, when it is not clear up-front
how will the loop end, is more interesting:

  my $k = 0;
  for $k (0..9) {
    # say $k;
	last if rand() < 0.2;
  }
  say $k;  # always 0

  my $q = 0;
  for ($q=0; $q <= 9; $q++) {
    # say $q;
	last if rand() < 0.2;
  }
  say $q; # some random number between 0 - 9

I think this is what Roman suggested.

Gabor


More information about the Perl mailing list