This blog no longer exists.
You will be redirected to something cool.

Friday, September 2, 2011

Looping in Perl

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.)

I also learned about postincrements and preincrements which were (and still kind of are) a difficult concept for me. Eh, I may suck at it now, but I'll get better as I shove along. I also learned about some flow control concepts like last, redo, and next. I only really covered 'last' in my coursework but as I move ahead I'll better understand flow control.

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;