子函数的 Perl 哈希 [英] Perl Hash of Subfunctions
问题描述
我希望有一个包含对子函数的引用的散列,我可以在其中根据用户定义的变量调用这些函数,我将尝试给出我正在尝试做的事情的简化示例.
I wish to have a hash containing references to sub-functions where I can call those functions dependent upon a user defined variable, I will try and give a simplified example of what I'm trying to do.
my %colors = (
vim => setup_vim(),
emacs => setup_emacs(),
)
$colors{$editor}(arg1, arg2, arg3)
其中 setup_vim()
和 setup_emacs()
将是稍后在我的文件中定义的子函数,而 $editor
是用户定义的变量(即 vim 或 emacs).这可能吗?我无法让它工作,或者找不到关于这个主题的好信息.谢谢.
where setup_vim()
and setup_emacs()
would be sub-functions defined later in my file and $editor
is a user defined variable (ie vim or emacs). Is this possible? I can't get it working, or find good information on the subject. Thanks.
(请注意,我现在将它实现为一个有效的 Switch,但我认为像上面这样的哈希可以更容易地向我现有的代码中添加新条目)
(Note I have it implemented right now as a working Switch, but I think a hash like the above would make it easier to add new entries to my existing code)
推荐答案
这里是语法.
my %colors = (
vim => \&setup_vim,
emacs => \&setup_emacs,
);
$colors{$editor}(@args)
请注意,您实际上可以直接使用
Note that you can actually create functions directly with
my %colors = (
vim => sub {...},
emacs => sub {...},
);
如果您熟悉闭包,Perl 支持已按词法声明的变量的完整闭包,您可以使用 my.
And if you're familiar with closures, Perl supports full closures for variables that have been declared lexically, which you can do with my.
这篇关于子函数的 Perl 哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!