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

时间:2015-08-12 15:56:47

标签: perl subroutine perl5

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

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等。除了那当然不起作用。

2 个答案:

答案 0 :(得分:6)

您可以构建子程序的调度表。像这样的东西

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 @_
}

答案 1 :(得分:0)

可以在没有桌子的情况下完成:

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

    # does stuff to @fooed
}