在Perl中给出另一个模块中的函数的引用

SIM*_*MEL 2 perl tk-toolkit reference perl-module

我想在Perl中使用Tk创建一个小GUI,它将有2个按钮:RaceQuit.

我希望Race按钮能够运行位于模块中的函数Car并被调用Race.

我写了以下代码:

#!/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;
Run Code Online (Sandbox Code Playgroud)

它可以工作,但是对我来说,制作一个只能调用另一个子程序的未命名子程序似乎很愚蠢.但是当我试图使用它-command => sub Car->Race(),-command => sub \&Car->Race(),它没有工作.

我明白这是因为我没有传递对函数的引用.如何将引用传递给位于另一个命名空间(模块)中的函数?

ike*_*ami 7

Car->Race()
Run Code Online (Sandbox Code Playgroud)

是相同的

Car->can('Race')->('Car');
^^^^^^^^^^^^^^^^   ^^^^^
sub ref            args
Run Code Online (Sandbox Code Playgroud)

如您所见,参数传递给sub.如果您不想使用anon sub,则必须指示Tk传递该参数.Tk确实有办法做到这一点.

-command => [ Car->can('Race'), 'Car' ],
Run Code Online (Sandbox Code Playgroud)

这可能会或可能不会快一点,但它肯定不是那么清楚

-command => sub { Car->Race() },
Run Code Online (Sandbox Code Playgroud)

至于其他包中的子程序?如果你有一些被称为使用的东西

Car::Race();
Run Code Online (Sandbox Code Playgroud)

它将被称为使用

-command => \&Car::Race,
Run Code Online (Sandbox Code Playgroud)

但这不是你在这里所拥有的.

* - 使用的模块除外AUTOLOAD.这就是自动加载器应该覆盖的原因can.