问题描述
我写了下面的Perl类:
I wrote the following Perl Class:
package Menu;
use strict;
my @MENU_ITEMS;
my $HEADER = "Pick one of the options below\n";
my $INPUT_REQUEST = "Type your selection: ";
sub new {
my $self = {};
$self->{ITEM} = undef;
$self->{HEADER} = undef;
$self->{INPUT_REQUEST} = undef;
bless($self);
return $self;
}
sub setHeader {
my $self = shift;
if(@_) { $self->{HEADER} = shift }
$HEADER = $self->{HEADER}."\n";
}
sub setInputRequest {
my $self = shift;
if(@_) { $self->{INPUT_REQUEST} = shift }
$INPUT_REQUEST = $self->{INPUT_REQUEST}." ";
}
sub addItem {
my $self = shift;
if(@_) { $self->{ITEM} = shift }
push(@MENU_ITEMS, $self->{ITEM});
}
sub getMenu {
my $formatted_menu .= $HEADER;
my $it=1;
foreach(@MENU_ITEMS) {
$formatted_menu.=$it.". ".$_."\n";
$it++
}
$formatted_menu.=$INPUT_REQUEST;
return $formatted_menu;
}
1;
如果我调用以下perl脚本:
If I call the following perl script:
#!/usr/bin/perl
use strict;
use Menu;
my $menu = Menu->new();
$menu->addItem("First Option");
$menu->addItem("Second Option");
print $menu->getMenu;
我会得到以下输出:
Pick one of the options below
1. First Option
2. Second Option
Type your selection:
我想以一种方式修改给定的类,以便将第二个参数传递给方法 addItem()
I'd like to modify given class in a way that I can pass a second argument to the method addItem()
类似于:
$ menu-> addItem(First Option,& firstOptionFunction ());
和当且仅当 第一选项
被选中,然后执行 $ firstOptionFunction
。
and if and only if First Option
is selected, then $firstOptionFunction
is executed.
有没有办法在Perl中实现这种行为?
Thanks!
Is there any way to achieve such behavior in Perl?Thanks!
推荐答案
您希望到子例程。
$menu->addItem("First Option", \&firstOptionFunction);
您的addItem方法可能如下所示:
And your addItem method might look like this:
sub addItem { ## your logic may vary
my ( $self, $option, $code ) = @_;
if ( $option eq 'First Option' ) {
$code->();
}
$self->{ITEM} = $option;
push @MENU_ITEMS, $option;
return;
}
正如您在注释中提到的,您可能不希望将子例程作为一个参考,而是将它存储在别的地方。这样的事情可能会奏效:
As you mentioned in the comments, you might want to not pass the subroutine as a reference, but rather store it somewhere else. Something like this might work:
sub new {
my $class = shift;
my $self = bless {}, $class;
$self->{f_o_code} = \&firstOptionFunction; ## use a better name than f_o_code
return $self;
}
## add your other methods
sub addItem { ## your logic may vary
my ( $self, $option ) = @_;
if ( $option eq 'First Option' ) {
$self->{f_o_code}->();
}
$self->{ITEM} = $option;
push @MENU_ITEMS, $option;
return;
} ## call like $menu->addItem( 'First Option' );
这篇关于在Perl中,我如何传递一个函数作为另一个函数的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!