Jorgen Jorgen - 5 months ago 14
Perl Question

How do I execute a Tk-Canvas function stored as a reference in a hash table?

I am trying to execute a Tk-function stored as a reference to a function in a hash table. In the very simplified example below, the code should draw a big red dot (i.e. do what line 14 does). I can't make a valid reference to createOval(), neither with $w-> in the hash table, nor with it moved down to line 13. I have googled for this high and low, but to no avail. What am I missing?

If I treat $w->... as a reference, the error message is "wrong number of args: ..." and if I stuff \& in front of $w in line 10: "Not a CODE reference at a11.pl line 9."

This is dead easy to do in Python: just stuff w.create_oval into the dictionary and it works.

use strict;
use warnings;
use Tk;

my $mw = MainWindow->new;
my $w = $mw->Canvas(-width => 1200, -height => 800);
$w->pack;

my %xfun = (
'b' => $w->createOval
);

$xfun{'b'}(200, 200, 250, 250, -fill=>'red');
#$w->createOval(200, 200, 250, 250, -fill=>'red');

MainLoop;

Answer

The following seems to work:

use strict;
use warnings;

use Tk;

my $mw = MainWindow->new;
my $w = $mw->Canvas(-width => 1200, -height => 800);
$w->pack;

my %xfun = (
    b => sub { $w->createOval(@_); },
);

$xfun{b}->(200, 200, 250, 250, -fill=>'red');

MainLoop;

Note:

I assumed that your original call:

$xfun{'b'}(200, 200, 250, 250, -fill=>'red');

did not work because it missed the object $w as first arg, but when I tried passing $w explicitly as the first argument:

$xfun{'b'}($w, 200, 200, 250, 250, -fill=>'red');

it still did not work.. I got error:

wrong # args: should be ".canvas create oval coords ?arg arg ...?"
Comments