7

我写了以下 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 中实现这种行为?谢谢!

4

1 回答 1

8

您可能希望传递对子例程的引用。

$menu->addItem("First Option", \&firstOptionFunction);

您的 addItem 方法可能如下所示:

sub addItem { ## your logic may vary
    my ( $self, $option, $code ) = @_;
    if ( $option eq 'First Option' ) {
        $code->();
    }

    $self->{ITEM} = $option;
    push @MENU_ITEMS, $option;

    return;
}

正如您在评论中提到的,您可能不想将子例程作为参考传递,而是将其存储在其他地方。像这样的东西可能会起作用:

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' );
于 2012-05-09T20:25:37.640 回答