在 perl 中保存音译表
我想用 0 音译 1 - 8 的数字,但在编译时不知道数字。由于音译不会插入变量,所以我这样做:
@trs = (sub{die},sub{${$_[0]} =~ tr/[0,1]/[1,0]/},sub{${$_[0]} =~ tr/[0,2]/[2,0]/},sub{${$_[0]} =~ tr/[0,3]/[3,0]/},sub{${$_[0]} =~ tr/[0,4]/[4,0]/},sub{${$_[0]} =~ tr/[0,5]/[5,0]/},sub{${$_[0]} =~ tr/[0,6]/[6,0]/},sub{${$_[0]} =~ tr/[0,7]/[7,0]/},sub{${$_[0]} =~ tr/[0,8]/[8,0]/});
然后将其索引为:
$trs[$character_to_transliterate](\$var_to_change);
如果有人能给我指出一个最好看的解决方案,我将不胜感激。
I want to transliterate digits from 1 - 8 with 0 but not knowing the number at compile time. Since transliterations do not interpolate variables I'm doing this:
@trs = (sub{die},sub{${$_[0]} =~ tr/[0,1]/[1,0]/},sub{${$_[0]} =~ tr/[0,2]/[2,0]/},sub{${$_[0]} =~ tr/[0,3]/[3,0]/},sub{${$_[0]} =~ tr/[0,4]/[4,0]/},sub{${$_[0]} =~ tr/[0,5]/[5,0]/},sub{${$_[0]} =~ tr/[0,6]/[6,0]/},sub{${$_[0]} =~ tr/[0,7]/[7,0]/},sub{${$_[0]} =~ tr/[0,8]/[8,0]/});
and then index it like:
$trs[$character_to_transliterate](\$var_to_change);
I would appreciate if anyone can point me to a best looking solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每当你重复自己时,你应该看看你正在做的事情是否可以循环完成。由于
tr
在编译时创建其表,因此您可以使用eval
在运行时访问编译器:这里也不需要使用引用,子例程参数已经通过参考。
如果您不想使用字符串 eval,则需要使用支持运行时修改的构造。为此,您可以使用
s///
运算符:tr///
构造比s///
更快,因为后者支持正则表达式。Any time that you are repeating yourself, you should see if what you are doing can be done in a loop. Since
tr
creates its tables at compile time, you can useeval
to access the compiler at runtime:There is also no need to use references here, subroutine arguments are already passed by reference.
If you do not want to use string eval, you need to use a construct that supports runtime modification. For that you can use the
s///
operator:The
tr///
construct is faster thans///
since the latter supports regular expressions.我建议简单地放弃
tr
,转而使用实际上允许一点元编程的东西,例如s///
。例如:这非常简单。 :)
I'd suggest simply ditching
tr
in favor of something that actually permits a little bit of metaprogramming likes///
. For example:which is surprisingly straightforward. :)
这是一个使用替换而不是音译的简短子例程:
Here's a short subroutine that uses substitution instead of transliteration: