有没有办法通过传递给另一个子程序的参数来选择子程序?像这样:
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
等。除了那当然不起作用。
答案 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
}