11. Common Problems.

Everything in Tk-land is a reference. When defining callbacks take care to pass variables by reference. Callbacks are closures and to ensure a variable gets its current value, as opposed to its value when the callback is defined, pass by reference, e.g.:

    $frog = 123;
    $b = $mw->Button(
        -text    => 'Push Me',
        -command => [
            sub {
               my($widget, $frog) = @ARG;
               print STDERR "widget=$widget!\n";
               print STDERR "frog=$$frog!\n";
            }, $mw, \$frog,
         ],
    ); # end Button definition

If $frog is not passed by reference the print statement will always output "123" (actually, the print as it exists will print nothing since it's trying to dereference $frog, which presumably is now not a reference). Note that by definition all perl/Tk widgets are already references, since they're simply Perl objects, and that's why you do not have to print $$widget!

A good "reference" for handling references and dereferencing are the perlref(1) and perlobj(1) man pages. A good "reference" for the various data types you will encounter in this kind of perl programming is Tom Christiansen's Perl Data Structures Cookbook which is now available as the perldsc(1) man page.

Also beware the traps that befall perl4 programmers in making the move to perl 5. References for this include the new perltrap(1) man page as well as William Middleton's perl425 trap document at:

    http://www.perl.com/perl/all_about/perl425.html
or
    http://w4.lns.cornell.edu/~pvhp/ptk/misc/perl425.html

Previous | Return to table of contents | Next