2012-08-06 80 views
8

我正在学习perl Inline :: Python库。在CPAN网站的例子,我们有Perl Inline :: Python模块,如何将代码放入字符串

print "9 + 16 = ", add(9, 16), "\n"; 
    print "9 - 16 = ", subtract(9, 16), "\n"; 

    use Inline Python => <<'END_OF_PYTHON_CODE'; 
    def add(x,y): 
     return x + y 

    def subtract(x,y): 
     return x - y 

    END_OF_PYTHON_CODE 

是否有可能把Python代码转换为字符串,这样我可以创建在运行时Python代码?例如,像这样的东西:

my $python_code = " 
def add(x,y): 
    return x + y 
"; 
print $python_code; 
use Inline Python => "$python_code"; 
print "9 + 16 = ", add(9, 16), "\n"; 

我们有一个项目,将在运行时动态创建python函数。我们想调用这些函数。 py_eval()是否要走?提前致谢。

+0

你嵌入Python解释器? – 2012-08-06 18:52:34

+0

是的,有点。我们的perl程序需要运行在运行时创建的python函数。 – biajee 2012-08-06 20:07:41

回答

4

没有与Inline::Python经验,但与Inline::Cyou can use the bind function to set code at runtime,所以也许这将工作:

my $python_code = " 
def add(x,y): 
    return x + y 
"; 
print $python_code; 
Inline->bind(Python => $python_code); 
print "9 + 16 = ", add(9, 16), "\n"; 
+0

你说得对。这工作。非常感谢你的暴民。 – biajee 2012-08-06 20:05:17

相关问题