Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Inline::Python module, how to put code into a string

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.

like image 606
biajee Avatar asked Aug 06 '12 17:08

biajee


People also ask

How do you write an inline code in Python?

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).

What is the use of inline is Python?

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.


1 Answers

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";
like image 139
mob Avatar answered Nov 07 '22 18:11

mob