in reply to Binding Tk events

Ok, I've been a bit whacky today regarding this node.
Maybe its because I had to work all weekend and everyone else was on vacation :).

I will post this on the "Tk Binding mouse down" node since it is the same issue.

here is the clarification for Calling subs/functions from tk bound widgets:

subs/functions can be called in 3 basic ways as the following code will demonstrate.
1) directly
2) using the sub function
3) using an anonymous array

If you want to pass arguments to the called sub you will need to use method 2 or 3.

The code below demonstrates these 3 three methods.
Notice closely the difference between what happens in the subs called by $button2 and $button4. Specifically, $button4 requires an initial shift; because an anonymous array is being used. Without this shift the print statement in the sub would attempt to print the tk::button information (which is stored in a hash).

code
use Tk; use strict; my $mw = MainWindow->new(); my $button1 = $mw->Button(-text => "on release 1")->pack(); $button1->bind('<ButtonRelease 1>' => \&doit1 ); my $msg = "pressed 2"; my $button2 = $mw->Button(-text => "on realease 2")->pack(); $button2->bind('<ButtonRelease 1>' => sub { \&doit2($msg) } ); my $button3 = $mw->Button(-text => "on release 3")->pack(); $button3->bind('<ButtonRelease 1>' => [\&doit3]); my $msg1 = "pressed 4"; my $button4 = $mw->Button(-text => "on release 4")->pack(); $button4->bind('<ButtonRelease 1>' => [\&doit4, $msg1]); MainLoop; sub doit1(){ print "pressed 1\n"; } sub doit2(){ my $msg = shift; print "$msg\n"; } sub doit3(){ print "pressed 3\n"; } sub doit4(){ shift; my $msg = shift; print "$msg\n"; }

output from pressing each button in order:
pressed 1 pressed 2 pressed 3 pressed 4

Finally, any thoughts about putting this in the tutorials or Q&A section? Or is it not up to par?

davidj