Solved

python to perl (convert or translate or parse)

Posted on 2003-11-19
17
2,330 Views
Last Modified: 2012-06-27
hi, does anyone know (or have any information on) how to convert/translate and/or parse a python code into perl? or is it too ambiguous to do so? i need to at least parse a phyton code into perl....does anyone know where i might find (or how i might do it) easyly? i mean..i could do it with tons of regular expressions n stuff.....but is there any other way?
thanks
0
Comment
Question by:Traltixx
  • 7
  • 6
  • 4
17 Comments
 
LVL 20

Expert Comment

by:jmcg
ID: 9787633
In the time it would take to do a good job of this, you could have a working Parrot. Parrot is the project to write a common backend for scripting languages like Perl, Python, and Ruby and is already part of the plans for Perl6.

Meanwhile, maybe you could say a bit more about what your immediate need is so we can maybe offer sensible approaches. It is impractical to mechanically translate a whole Python application into Perl. But if you just have some small pieces of Python that are built according to some template, we may be able to suggest a way to re-interpret those snippets into working Perl.
0
 
LVL 2

Author Comment

by:Traltixx
ID: 9792293
well...i have to translate or at least parse whoe of python to perl...i mean id input a python sourcecode and get a perl translation..saying which are variables, which are if statement (and where to go if a certain condition), where to loop and where are subroutines (and where they are called and returned)...thus the template for input would probably be a python sourcedcode that has these elements in them..and perl will try to at least break it up and translate it. as i am unfamiliar with python, how can this be acomplished?

btw, when is perl 6 and parrot going to be released?
0
 
LVL 20

Expert Comment

by:jmcg
ID: 9793367
Oh, the release of Perl6 and Parrot is not coming very soon, but to do a general job of translating would take a long time, too.

Let's back up a few steps. Why do you believe you need to translate Python into Perl? Python will run in all the same places that Perl does. If you have a standard Python library that you're dealing with, there may well be a closely equivalent Perl library available to do the same thing. You can run a Python script from perl and vice versa. So please explain a bit more and maybe we can come up with an answer for you.
0
 
LVL 2

Author Comment

by:Traltixx
ID: 9794169
well...the thing is i need to read a python/perl sourcecode process it the perl way...thus whatever the sourcecode was, the perl translator will understand and process it...that is essentially what i want to do
thanks
0
 
LVL 20

Expert Comment

by:jmcg
ID: 9794632
Since I cannot figure out what you are trying to do, and you won't tell me, all I can do is wish you the best of luck.
0
 
LVL 2

Author Comment

by:Traltixx
ID: 9795114
sigh..ok..i was just trying to build a perl script that would take a python code n output its perl equivalent (parts that arent  translateable or arent implemented in perl will be ignored and commented). im doing this as a starting point for a universal translator....anyway..any other helpers?
0
 
LVL 2

Expert Comment

by:ext2
ID: 9803623
I have experience using the Parse::RecDescent module (http://search.cpan.org/dist/Parse-RecDescent/lib/Parse/RecDescent.pod , http://www.perl.com/pub/a/2001/06/13/recdecent.html) to compile a language into bytecodes.  You might alternatively try Parse::Yapp, or one of the other parsing/lexing modules available on CPAN.  However, be warned that implementing such a compiler/translator is not an easy task.  It took me a couple of weeks to implement a language that was fairly basic yet robust.  Getting the compiler to work on some correct types of input is easy (a few days); getting the compiler to recognize all good input and cleanly fail on all bad input is much harder.

As an interesting sidenote, here's a (partially implemented) Perl-to-Python translator:

  http://www.crazy-compilers.com/

It uses a modified B::Deparse module.  When translating as such between high-level languages for the purpose of the generated code to be read by humans, there is a need for generated Python code to not just exectute but to look Pythonic rather than as Python code written in Perlisms.  Otherwise, you minus well just embed a real Python interpreter into Perl.  I would think that implementing a Perl-to-Python translator would be much harder than doing the reverse since Perl has a much richer syntax.  So, I have some doubts on whether Perl-to-Python translation is even a useful/possible pursuit.  A Python-to-Perl translator would have the advantage than Pythonic code is easier to express in Perl than vice-versa.  Parrot seems to be the way to go.

I don't think you've told us though essentially why you feel the need to perform automated Python-to-Perl translation.  It's big task, and there must be some justification for expending the effort.  It does sound like an interesting project, which I may be willing to help on developing a CPAN module if others are interested.  :)

Also of interest are various CPAN modules for easing Perl-Python integration:
  http://search.cpan.org/search?query=python&mode=all
Most take the (sensible) approach of embedding a Python interpreter into Perl rather than trying to reimplement Python in Perl (similar to Jython, which reimplements Python on the Java VM).  However, none of these are intended as source-code translators.
0
 
LVL 2

Author Comment

by:Traltixx
ID: 9804587
thanks for the comments....firstly, the project is part of a user-friendly debugger....the only part left if the input section which takes python (or other languages) or perl and debugs it in perl.
anyway,ive looked into YAPP, and it doesnt seem to parse python....(or i didnt find a way how to)
and yes, i do think translating perl to python is a much harder task, thats why the main script/program will be written in perl instead of python.......
anyway, whats wrong with source-code translators? arent there any? i mean, thats the whole point....
oh well..thanks for your help....does anyone have any other ideas?
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 2

Author Comment

by:Traltixx
ID: 9804607
also on a side note the Parse::RecDescent  looks promising, but is there a way to convert it to perl no matter what bytecods it is from. anyway, just wondering...thanks again for your help
0
 
LVL 2

Accepted Solution

by:
ext2 earned 90 total points
ID: 9804864
There are source code translators.  I haven't used any, but ANTLR (www.antlr.org), which has lots of good info on its web site, has been used to build some such translators (e.g. VB --> C#: http://www.immunicode.com/).

To build a Python recognizer (using Parse::RecDescent, Parse::Yapp, ANTLR, or whatever), the place to start is with the Python grammar:

   http://www.python.org/doc/current/ref/grammar.txt

Convert this grammar into the format needed by the particular tool so that the tool can build a parse tree.  Then add the necessary code to convert that parse tree into Perl source code.

In fact, you you may have inspired in this direction.  I'm converting grammar.txt into the format needed by Parse::RecDescent and have begun adding some action handlers to translate Python assignment_stmt's to corresponding Perl code.  For example, here's one crude rule so far:

# original Python rule:
# or_test ::=
#              and_test | or_test "or" and_test
 
or_test : and_test(s /or/)
{
    my $ands = $item{'and_test(s)'};
    my $perl = join(' or ', map "$$_{perl}", @$ands);
    {perl => $perl}
}

Actually, this rule would translate the Python "1 or 0 or 1" into the equivalent Perl "1 or 0 or 1" (not very interesting!).

If I maintain interest, I'll post a link to the code here.  My impetus for doing this is so that the next time a Python user says "The Python syntax is so much cleaner than the Perl line-noise, and everyone should use Python," we Perl monks can wrap the Python-->Perl translator in a Filter::Simple and respond,

  #!/usr/bin/perl
  use PythonFilter;

  def hello(who):
      print "Hello", who, ", there's more than one way to do it!"

  hello("world!")

> also on a side note the Parse::RecDescent  looks promising,
> but is there a way to convert it to perl no matter what bytecods
> it is from

The two "its" seem ambiguous in reference, but Parse::RecDescent is a Perl module written entirely in Perl.  You feed Parse::RecDescent a grammar file or string (having syntax similar to the grammar.txt above) that also contains actions (Perl code blocks that get executed when grammar rules are matched).  These actions must be written to generate corrsponding Perl code at various stages in the parse of the Python code.  Parse::RecDescent uses this specification to generate the Perl code for a corresponding compiler.  You can import the generated compiler into your own program since the compiler is simply a Perl module.  You then would feed in Python code into that compiler, which would spit out the corresponding Perl code.
0
 
LVL 2

Expert Comment

by:ext2
ID: 9805074
Here's my very initial implementation:

   http://www.math2.org/perthon/

input:

x = 5
y = 2+3**3
x,y = 1+2,3
while x > 3: x = x+1

output:
$x = 5;

$y = 2 + 3**3;
($x, $y) = (1 + 2, 3);
while($x > 3) {
$x = $x + 1;
}
0
 
LVL 2

Author Comment

by:Traltixx
ID: 9808239
wow......well, at least its a start..i dont get one bit tho..u said
"If I maintain interest, I'll post a link to the code here.  My impetus for doing this is so that the next time a Python user says "The Python syntax is so much cleaner than the Perl line-noise, and everyone should use Python," we Perl monks can wrap the Python-->Perl translator in a Filter::Simple and respond,"
meaning that it would be easier to code/understand in perl rather in python?
anyway...it is interesing (tho some parts of creating a module i still dont get..but ill leave that for another thread)..
but the python grammer
u gave the link for..is that all the python grammar or only some of it? because i would expect python to have much more....
anyway..whats next? so i can get into it as well....and thanks for sharing the initial implementation
0
 
LVL 2

Expert Comment

by:ext2
ID: 9814734
Perl allows the use of custom preprocessors in order to extend the language (e.g. by using Filter::Simple as described on http://search.cpan.org/~dconway/Filter-Simple-0.79/lib/Filter/Simple.pm).  My idea is that we wrap the Python --> Perl translator in such a filter so that it is really convenient to use.  You could even mix Perl and Python code within the same source file (if you really wish, even though it might not be in good design taste--Perl in Python are probably best kept in separate files).  It's kind-of like the .NET/JVM/Parrot concept on the existing Perl 5.x runtime.

==============
sub hello {
    return "hello";
}

&world();

use Python;

def world():
    print hello(), "world"
==============

But the main benefit is seemless intergration between Perl and Python-like code.  A Python-like program could directly manipulate a Perl hash or invoke code from Perl CPAN modules.  Maybe we can even entice back those who have strayed away from Perl into the land of Python.

The Python grammar is complete (yes, it is fairly simple, which is good for Perthon).  It's linked from the authoritative Python Language Reference (http://www.python.org/doc/current/ref/ref.html), which would include anything else that's needed (e.g. tokenization rules).

If I continue to maintain interest, I'll post this on sourceforge or something.  For any interim updates, I'll note them here.
0
 
LVL 20

Expert Comment

by:jmcg
ID: 9815478
I'll cheerfully admit I was wrong. I can't say how impressed I am with what you've done, Ext2!
0
 
LVL 2

Expert Comment

by:ext2
ID: 9822689
Made some good progress tonight.  The pre-pre-alpha Perthon compiler is now partly usable and packaged for download.  As seen from the grammar file, some major constructs are still missing, like, um, if statements.  However, if you really need an if statement, you can tentatively rewrite it as a while ;)  If you have any questions, read the source code!
0
 
LVL 2

Author Comment

by:Traltixx
ID: 9839033
well...ok..firstly im on vacation (for 3 months) so id have to pause this for a sec.....but ill give u the point anyway and ill resume (or start) on it as soon as i get back (btw..i dont have my perl on my pc now..so i cant rest anything)
thanks very much for your help
0
 
LVL 2

Expert Comment

by:ext2
ID: 9856182
Just to let everyone know, Perthon is now on SourceForge:

  http://perthon.sourceforge.net/

And thanks, Traltixx, for bringing up the idea!
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This video discusses moving either the default database or any database to a new volume.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now