gpt4 book ai didi

perl - 在 Perl 中引用另一个模块中的函数

转载 作者:行者123 更新时间:2023-12-02 06:22:11 25 4
gpt4 key购买 nike

我想在 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;

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

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

最佳答案

Car->Race()

与*相同

Car->can('Race')->('Car');
^^^^^^^^^^^^^^^^ ^^^^^
sub ref args

如您所见,一个参数被传递给子程序。如果您不想使用匿名子,则必须指示 Tk 传递该参数。 Tk 确实有办法做到这一点。

-command => [ Car->can('Race'), 'Car' ],

这样可能会快一点,也可能不会快一点,但绝对没有

-command => sub { Car->Race() },

至于其他包中的子程序?如果你有一个叫做 using 的东西

Car::Race();

它将被调用为

-command => \&Car::Race,

但这不是你这里的。

* — 除了使用 AUTOLOAD 的模块。这就是自动加载器应该覆盖 can 的原因。

关于perl - 在 Perl 中引用另一个模块中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7321740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com