我写了以下 Perl 类:
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 脚本:
#!/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()
就像是:
$menu->addItem("First Option", &firstOptionFunction());
并且当且仅当 First Option
被选中时,然后$firstOptionFunction
被执行。
有没有办法在 Perl 中实现这种行为?谢谢!