我可以将带有参数的子程序存储在哈希中吗?

Can i store subroutines with parameters in a hash?

我正在 perl/tk 构建一个项目,它将允许启动计时器来跟踪项目工作。我对如何将按钮的命令存储为子例程但带有参数的问题停滞不前。由于正在执行带有参数的子程序,因此结果将存储为命令。

如何在散列中存储带参数的子例程,使其仅在按下按钮时执行。

#create buttons but dont pack them on the frame yet
my $info    = $mw->Button( -text => "Good",   -command => \&info_popup );
my $warning = $mw->Button( -text => "Caution", -command => \&warning_popup );
my $error   = $mw->Button( -text => "Bad",   -command => \&error_popup );
my $close   = $mw->Button( -text => "Close",   -command => \&close );
my $project1 = $mw->Button( -text => "project1", -command => \&start_timer("project1"));
my $project2 = $mw->Button( -text => "project2", -command => \&start_timer("project2"));

sub start_timer {
    my $project = shift;
    print "starting the timer for: $project\n";
}

我怀疑我正在尝试的事情是不可能的,所以希望您能帮助我实现一个符合这个标准的解决方案,即按下一个按钮将调用带有该按钮特定参数的子例程。

当使用 TK 时,oreilly 袖珍指南说

Perl/Tk Callbacks A callback is a scalar, either a code reference or a method name as a string. Either of these styles can take parameters by passing an array reference, with the first element the code reference or method name, and subsequent elements subroutine parameters. \&subroutine [\&subroutine ?, args?] sub {...} [sub {...} ?, args?] ’methodName’ [’methodName’ ?, args?] Note that bind callbacks are implicitly passed the bound widget reference as the first argument of the parameter list. Refer to the section Bindings and Virtual Events for related information.

我使用下面的代码对此进行了测试,它按预期工作

#create buttons but dont pack them on the frame yet
my $info    = $mw->Button( -text => "Good",   -command => \&info_popup );
my $warning = $mw->Button( -text => "Caution", -command => \&warning_popup );
my $error   = $mw->Button( -text => "Bad",   -command => \&error_popup );
my $close   = $mw->Button( -text => "Close",   -command => \&close );
my $project1 = $mw->Button( -text => "project1", -command => [\&start_timer,"project1"]);
my $project2 = $mw->Button( -text => "project2", -command => [\&start_timer,"project2"]);

sub start_timer {
    my $project = shift;
    print "starting the timer for: $project\n";
}