logo       
Google Custom Search
    AddThis Social Bookmark Button
-->

Question about a dynamic Tk:bind: msg#00054

Subject: Question about a dynamic Tk:bind
Hello,

In fact I got a solution to my problem, but I wonder to know if there is a 
nicer, simpler, or more elegant one.

The question : in a Tk::Entry ($entry), the key "Enter" is bounded to a 
routine (sub1 | sub2) dynamicly, according to the value of a variable ($num).
In the program below, when typing the "Enter" key, I am expecting this output:
sub1 num=0
sub2 num=1
sub1 num=0
sub2 num=1
...

my code:
----------------
#!perl -w
use strict;
use Tk;
my $num = 0;
my @sp = (\&sub1, \&sub2); # array of sub's refs
my $mw = MainWindow->new;
my $entry = $mw->Entry->pack;
$entry->focus;
$entry->bind(
        "<Key-Return>" => sub { &{$sp[$num]} }  # this work
#       "<Key-Return>" => $sp[$num]             # this don't work, ($sp[$num] 
seems bounded to \$sp[0] which is \sub1)
);
MainLoop;
sub sub1 {
        print "sub1 num=$num\n";
        $num = 1;
}
sub sub2 {
        print "sub2 num=$num\n";
        $num = 0;
}
----------------

The reason for my post (if you want one): while it is possibly the simplest 
one, I don't like "sub {&{$sp[$num]}}" because $sp[$num] is a reference to a 
routine (sub1 or sub 2, depending on $num), which is de-referenced by "&{}", 
which is re-referenced by the anonymous sub{}

Maybe it is the price to pay for ?
Or is the answer in Tk::callbacks ? (where I read that callbacks may have 
three forms, \&sub, sub{} or 'methodname')

Thanks in advance,
Jean-Pierre

-- 
Jean-Pierre Vidal

-++**==--++**==--++**==--++**==--++**==--++**==--++**==
This message was posted through the Stanford campus mailing list
server.  If you wish to unsubscribe from this mailing list, send the
message body of "unsubscribe ptk" to majordomo@xxxxxxxxxxxxxxxxxx



<Prev in Thread] Current Thread [Next in Thread>