I am learning perl Inline::Python library. In the example of cpan website, we have
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
Is it possible to put python code into string so that I can create the python code in the runtime? For example, something like:
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";
We have a projects that will dynamically create python functions at the runtime. And we want to call these functions. Is py_eval() the way to go? Thanks in advance.
Giving Your Source to Inlineuse Inline Python => << 'END' ; Python source code goes here. The source code can also be specified as a filename, a subroutine reference (sub routine should return source code), or an array reference (array contains lines of source code).
An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.
No experience with Inline::Python
, but with Inline::C
you can use the bind
function to set code at runtime, so maybe this will work:
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With