I just got done with a chapter (and homework) on writing loops in Perl. Surprisingly, it was significantly easier than any other chapter I'd done yet. Perhaps this is due to the amount of time (a ton) learning loops when I first started learning programming (Ruby.)
So here is some sample code (in Ruby) that is strikingly similar to some code a friend wrote for me in order to pound the concept of loops into my head years ago. So on to the code:
i = 0 while i < 12 puts i.to_s i = i + 1 end
And here's how I learned to write this in Perl:
#!/usr/bin/perl use strict; use warnings; my $i = 0; while ( $i <= 12 ) { print $i, "\n"; $i = $i + 1; }
2 comments:
Hi! A slightly more idiomatic Perl version might be:
#!/usr/bin/perl
use 5.014;
use strict;
use warnings;
for my $i (1..12) {
say $i;
}
If you really want to do the separate initialization, you could use the c-style for:
#!/usr/bin/perl
use 5.014;
use strict;
use warnings;
for (my $i = 0; $i < 12; $i++) {
say $i;
}
Incidentally, you shouldn't worry too much about pre- and post-increments. In fact, there are some recent suggestions that you would be better off not using them. Instead, you can use:
$i += 1;
HTH,
Ricky
Idiomatic Perl will be like this
#!/usr/bin/perl
use 5.014;
use strict;
use warnings;
say for (1..12);
1;
Post a Comment