2012-08-06 41 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

相關問題