9.1. How do I get a Button to call a Perl subroutine?

You may specify the -command option in the call to create & pack the button as in:

    $main->Button(-text => 'Print',
                   -command => sub{do_print($filename, $font)}
                   )->pack;
Where sub do_print { } is a subroutine that handles two arguments and is declared elsewhere in the script. A full script example of the use of the above code is presented in the second example(s) in UserGuide.pod

(Full source code for this and other examples from UserGuide.pod may be found at http://w4.lns.cornell.edu/~pvhp/ptk/pod/. To load code from the web save as a local file say ex1.pl, edit the first line to point to your perl interpreter, then change permission: %chmod u+x ex1.pl, then execute the script: %ex1.pl.)

The above method is called the "anonymous subroutine (closure)" method. As discussed in Callback.pod one might have re-written that statement to use the "reference to a sub" method thusly:

    $main->Button(-text => 'Print',
                   -command => [ \&do_print , $filename, $font ]
                   )->pack;
Note the backslash in front of \&do_print. This causes perl to generate a reference to sub do_print rather than call it. (thanks Jim Stern :-)

Previous | Return to table of contents | Next