将参数传递给子例程的名称

Pass a parameter into the name of a subroutine

有没有办法通过传递给另一个子程序的参数来选择一个子程序?像这样:

sub foo1 {
    # does stuff to @_
}

sub foo2 {
    # does other stuff to @_
}

sub foo3 {
    # does other stuff to @_
}

sub foo {
    my $whichsub = shift;
    my @fooed = foo.$whichsub @_;
    # does stuff to @fooed
}

其中 foo.$whichsub 应该是 foo1 之类的。当然那是行不通的。

您可以构建子例程的分派 table。像这样

my @foo_table = \(&foo1, &foo2, &foo3);

foo(2);

sub foo {
    my $whichsub = shift;
    die unless my $foosub = $foo_table[$whichsub-1];
    my @fooed = $foosub->(@_);

    # does stuff to @fooed
}

sub foo1 {
    # does stuff to @_
}

sub foo2 {
    # does other stuff to @_
}

sub foo3 {
    # does other stuff to @_
}

不用table也可以做到:

sub foo {
    my $whichsub = shift;
    my $foosub = "foo".$whichsub;
    my @fooed = &$foosub(@_);

    # does stuff to @fooed
}