I want to make a small GUI using Tk in Perl that will have 2 buttons: Race and Quit.
I want the Race button to run a function that is located in a module Car and is called Race.
I’ve written the following code:
#!/usr/bin/perl -w
use strict;
use warnings;
use Car;
use Tk;
my $mw = MainWindow->new;
$mw->Label(-text => "The Amazing Race")->pack;
$mw->Button(
-text => 'Race',
-command => sub {Car->Race()},
)->pack;
$mw->Button(
-text => 'Quit',
-command => sub { exit },
)->pack;
MainLoop;
It works, but It seems stupid to me to make an unnamed subroutine that will just call another subroutine. But when I tried to use -command => sub Car->Race(), or -command => sub \&Car->Race(), it didn’t work.
I understand that this is because I’m not passing a reference to the function. How do I pass a reference to a function that is located in another namespace (module)?
This syntax is symple:
But if you need to pass any special arguments to that functions or call it as method, you still need an anon sub:
This one calls Race as method of package Car and pass all arguments to it.