例如,伪代码如下。根据x的输入,如果x为func1,则必须调用func1()。如果x为func2,则必须调用func2()。有没有办法做到这一点。我不想使用if或switch case语句。还有其他方法可以根据用户输入进行函数调用吗? (类似于将函数视为变量?
sub func1()
{...}
sub func2()
{...}
sub mainfunc()
{
x = <STDIN>;
x();
}
答案 0 :(得分:9)
好像您正在寻找dispatch table
RUN python3 -m pip install --upgrade pip
此处use warnings;
use strict;
use feature 'say';
my %option = (
o1 => sub { say "Code for func1, to run for key 'o1'"; },
o2 => sub { say "Code that should run for input 'o2'"; },
#...
);
my $input = <STDIN>;
chomp $input;
# Dereference the code-reference (run code) associated with $input value
$option{$input}->();
定义了一个anonymous subroutine并返回了一个reference to code。获取代码引用的另一种方法是使用语法为sub { ... }
的命名子引用。作为引用,它是(单值)标量类型,因此可以用作哈希值。
因此,当用户提供\&sub-name
时,引用(o1
)中的代码即为哈希中键sub { ... }
的值即{{1} }。
运行代码引用的语法非常类似于取消引用数组或哈希引用
o1
此处的标量变量$option{o1}
的代码参考为$ar->[0] # dereference array reference, for the first element
$hr->{key} # dereference hash reference, for value for key 'key'
$cr->(LIST) # dereference code reference, to run with arguments in LIST
。
答案 1 :(得分:6)
安全的方法是使用名称哈希来映射到子例程,这样恶意用户就无法调用任意子。像这样:
SomeServiceThing<T>