Perl 中函数的别名
在 Perl 中,如果我希望 foo()
完全执行 bar()
的操作,我可以这样做:
sub foo {return bar(@_);}
有更好的方法吗?更接近 Ruby 的“别名”运算符吗?
In Perl, if I want foo()
to do exactly what bar()
does, I can do this:
sub foo {return bar(@_);}
Is there a better way? Something closer to Ruby's "alias" operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Exporter
和类似模块采用的更好的方法是编辑符号表:(编辑是因为我们正在讨论的是 Perl)
TheA better way, employed byExporter
and similar modules, is to edit your symbol table:(edited because this is Perl we are talking about)
还有另一种方法可以做到这一点:
即使随后重新定义了
bar
,这也保留了foo
和bar
之间的等效性。这是一个详细的演示:
打印
There is another way to do it:
This preserves the equivalence between
foo
andbar
even ifbar
is subsequently redefined.Here is a detailed demo:
which prints
分配对 glob 的引用会将 glob 的该部分替换为所引用的事物。所以这使得 &foo 与 &bar 完全相同。
这也有效,但也为 foo 和 bar 之间的标量、数组、散列、文件句柄和格式设置别名。
Assigning a reference to a glob replaces that portion of the glob with the thingy referred to. So this makes &foo exactly the same as &bar.
This also works, but also aliases the scalar, array, hash, filehandle, and format between foo and bar.
由 Perlmonks 提供:
Courtesy Perlmonks: