Creating a Callback

Perl/Tk has an expressive and well-defined callback syntax. Anywhere an option expects a callback, you can use this syntax. The most common option name is -command, but you’ll also see -validatecommand, -browsecmd, or something similar. For instance, when you create a Button widget, you use -command to specify the callback invoked when the button is pressed. Similarly, when you create an event binding, you specify the event of interest and a callback to invoke when the event occurs.

At its simplest, a callback is a subroutine reference:

-command => \&callback

or:

-command => sub { ... }

The first example is a code reference to a named subroutine. The second is a code reference to an anonymous subroutine. Notice that you cannot pass explicit arguments to the subroutines using this callback format. A common mistake is to assume a statement of this form will work:

-command => \&callback(arguments)

Well, it “works” in the sense that it compiles and produces a result, but the result is probably not what you expect. You aren’t creating a code reference to a subroutine that will execute sometime in the future. Instead, the subroutine is executed immediately, and you get a reference to the subroutine’s return value. A fast session in the Perl debugger shows us the scary details:

[bug@Pandy Anatomy]$ perl -de 0 Default die handler restored. Loading DB routines from perl5db.pl version 1.07 Editor support available. Enter h or `h h' for help, or `man perldebug' for more ...

Get Mastering Perl/Tk now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.