我可以调用子程序,采取它的名字动态如下:在perl中调用函数的方法?
printf "Enter subroutine name:";
$var1=<STDIN>; #input is E111;
$var1();
E111:
sub E111(){
printf "Hi this is E111 & Bye \n";
}
是否有可能做这样的,我是新来的Perl编程。
我可以调用子程序,采取它的名字动态如下:在perl中调用函数的方法?
printf "Enter subroutine name:";
$var1=<STDIN>; #input is E111;
$var1();
E111:
sub E111(){
printf "Hi this is E111 & Bye \n";
}
是否有可能做这样的,我是新来的Perl编程。
在Perl中你可以做什么的限制很少,但是这是你不想去的地方之一。关于它的一个正常的方法是使用一个调度表
my %call = (
'name_1' => sub { function body }, # inline, anonymous subroutine
'name_2' => \&func, # or take a reference to a sub
...
);
其中sub {}
是匿名子,所以name_1
的值是一个码参考。
然后你把它作为
my $name = <STDIN>;
chomp $name;
$call{$name}->(@arguments); # runs the code associated with $name
这找到哈希键$name
和取消引用它的值时,CODEREF;所以它运行该代码。
文档:概述perlintro,教程perlreftut和参考文献perlref和perlsub。
A液:
print "Enter subroutine name:";
$var1 = <STDIN>;
chomp($var1);
eval "$var1()";
sub E111 {
print "Hi this is E111 & Bye \n";
}
按照@zdim的好的建议和使用调度表,但当然动态函数调用在Perl中是可能的:https://perldoc.perl.org/functions/eval .html – xxfelixxx
[从命令行调用perl子例程]的可能重复(http://stackoverflow.com/questions/23039028/calling-perl-subroutines-from-the-command-line) –