【发布时间】:2022-10-08 11:30:48
【问题描述】:
我是pythonizer 的作者,我正在尝试将perl 样式的函数模板转换为python。当我生成我认为等效的代码时,循环变量的值是最后一个值,而不是函数模板出现时的值。关于捕获正确循环变量值的代码有什么想法吗?例如:
# test function templates per the perlref documentation
use Carp::Assert;
sub _colors {
return qw(red blue green yellow orange purple white black);
}
for my $name (_colors()) {
no strict 'refs';
*$name = sub { "<FONT COLOR='$name'>@_</FONT>" };
}
assert(red("careful") eq "<FONT COLOR='red'>careful</FONT>");
assert(green("light") eq "<FONT COLOR='green'>light</FONT>");
print "$0 - test passed!\n";
被翻译成:
#!/usr/bin/env python3
# Generated by "pythonizer -v0 test_function_templates.pl" v0.978 run by snoopyjc on Thu May 19 10:49:12 2022
# Implied pythonizer options: -m
# test function templates per the perlref documentation
import builtins, perllib, sys
_str = lambda s: "" if s is None else str(s)
perllib.init_package("main")
# SKIPPED: use Carp::Assert;
def _colors(*_args):
return "red blue green yellow orange purple white black".split()
_args = perllib.Array()
builtins.__PACKAGE__ = "main"
for name in _colors():
pass # SKIPPED: no strict 'refs';
def _f10(*_args):
#nonlocal name
return f"<FONT COLOR='{name}'>{perllib.LIST_SEPARATOR.join(map(_str,_args))}</FONT>"
globals()[name] = _f10
print(red("careful"))
assert _str(red("careful")) == "<FONT COLOR='red'>careful</FONT>"
assert _str(green("light")) == "<FONT COLOR='green'>light</FONT>"
perllib.perl_print(f"{sys.argv[0]} - test passed!")
(我注释掉了nonlocal,因为python 抱怨这是一个语法错误,并添加了print 语句)。添加的print 语句写出<FONT COLOR='black'>careful</FONT> 而不是正确的<FONT COLOR='red'>careful</FONT>
当生成函数red 时,如何让它捕获循环计数器的red 值?
【问题讨论】:
-
CSS 现在过时了吗?
-
@北极熊:这只是 perl 文档中的示例代码