As programmers, we all know what a “main loop” is. It’s the heart of our programs, the repeating chunk of code that carries out the task at hand. But Perl/Tk programs are event driven, so even if we write what we believe is our program’s main loop, it must coexist with a higher order main loop that’s a fundamental part of Tk. The Tk main loop is typically referred to as the event loop, and its job is to invoke callbacks in response to events such as button presses or timer expirations.
Callbacks are Perl subroutines associated with Tk events. In Perl/Tk, we can define callbacks that, from our point of view, are automatically invoked when the appropriate event occurs. The Tk core defines hundreds of other callbacks on our behalf that we’re not even aware of. It’s the combination of our own callbacks and Tk-defined callbacks that gives behavior to our Perl/Tk applications.
The event loop is activated once the
MainLoop statement is
reached. From that point on,
MainLoop controls our
program. As events happen,
them to a handler (a callback) for processing and puts the
application to sleep for a short amount of time when the event queue
is empty. This repeats until there are no more MainWindows, at which
MainLoop returns. Any code after the
MainLoop statement is then executed.
Here is the salient portion of the actual
subroutine from the Perl/Tk source distribution:
use Tk ':eventtypes'; while ...