Thursday, July 30, 2009

adventures in ignorance: continue

So, what is a continue block and why would you want to use one? I have a habit of writing mini-daemonoid (for real daemons look at Proc::Daemon) scripts. Here is a trivial example:
#!/usr/bin/perl

use strict;
use warnings;

#wait to be killed by SIGTERM or a control-c
my $continue = 1;
local $SIG{INT} = local $SIG{TERM} = sub { $continue = 0 };
while ($continue) {
print "foo: ", time(), "\n";
sleep 1;
}
This works very well for most purposes, but it has a minor annoyance: if you say next in the body of the loop, you create a tight loop that will consume 100% of a CPU. The problem here is that we would skip the sleep statement that puts a break on the loop. That sleep statement is not really part of the body of the loop. It something extra that we want to execute each time through the loop. And that is what a continue block is: something that runs each time through the loop. For example, the following code prints "Hello World\n" five times despite the fact that the next statement skips to the next iteration:
#!/usr/bin/perl

use strict;
use warnings;

for (1 .. 5) {
print "Hello ";
next;
print "beautiful ";
} continue {
print "World\n";
}
This means we can use the continue block to solve the problem:
#!/usr/bin/perl

use strict;
use warnings;

#wait to be killed by SIGTERM or a control-c
my $continue = 1;
local $SIG{INT} = local $SIG{TERM} = sub { $continue = 0 };
while ($continue) {
print "foo: ", time(), "\n";
} continue {
sleep 1;
}
Even though we don't need it now, it is good practice to identify the portions of your loop that should always run, and move them into continue blocks. This servers as a hedge against some future enhancement that might want to use next and it is a useful clue to some later maintainer that the code is important.

No comments:

Post a Comment

Some limited HTML markup is allowed by blogger: strong, b, i, and a. You may also use em, but I have repurposed it through the magic of CSS to be behave very much like <tt><code></code></tt>.

Post a Comment