[英]Pass a parameter into the name of a subroutine
Is there a way to choose a subroutine by means of a parameter passed to another subroutine? 有没有一种方法可以通过传递给另一个子例程的参数来选择子例程? Something like this: 像这样:
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
}
where foo.$whichsub
should be foo1
or the like. 其中foo.$whichsub
应该是foo1
等。 Except that of course that doesn't work. 当然那是行不通的。
You can build a dispatch table of subroutines. 您可以构建子例程的调度表。 Something like this 像这样
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 @_
}
It can be done without a table: 无需表即可完成:
sub foo {
my $whichsub = shift;
my $foosub = "foo".$whichsub;
my @fooed = &$foosub(@_);
# does stuff to @fooed
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.