有什么方法可以在perl中将函数声明为变量? [英] Is there any way to declare a function as a variable in perl?
本文介绍了有什么方法可以在perl中将函数声明为变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,伪代码如下.根据x的输入,如果x为func1,则必须调用func1().如果x为func2,则必须调用func2().有什么办法可以做到这一点.我不想使用if或switch case语句.还有其他方法可以根据用户输入进行函数调用吗?(类似于将函数视为变量?
For example, Pseudocode is given below. Based on the input given to x, if x is func1, then func1() must be called. If x is func2, then func2() must be called. Is there any way to do this. I do not want to use if or switch case statements. Is there any other approach to make function call based on user input? (something like treating a function as a variable?
sub func1()
{...}
sub func2()
{...}
sub mainfunc()
{
x = <STDIN>;
x();
}
推荐答案
安全的方法是使用名称哈希来映射到子例程,这样恶意用户就无法调用任意子.像这样:
The safe way is to have a hash of names mapping to subroutines, so that arbitrary subs can't be called by a malicious user. Something like:
my %table = ("func1" => \&func1, "func2" => \&func2);
my $x = <STDIN>;
chomp $x;
if (exists $table{$x}) {
$table{$x}->();
} else {
# Handle error
}
这篇关于有什么方法可以在perl中将函数声明为变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文