且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Perl中,我如何传递一个函数作为另一个函数的参数?

更新时间:2022-12-14 19:27:30

您希望传递引用到子例程。

$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' );