Translating Perl to Python

News Python for Perl programmers Best books on compilers Recommended Links Pythonizer: two-pass "fuzzy" transformer from Perl to "semi-Python" Python Debugging    
Perl to Python functions map Perl special variable mapping to Python            
Program Analysis and Transformations Lexical analysis Recursive Descent Parsing Regular expressions Code  generation Tree-based code optimization Generative programming methods  Peephole optimization
Defensive programming LEX&YACC  Perl to Python functions map Python Braces Debate Prolog Bit Tricks Humor Etc

In a sense translation of Perl to Python is always manual, "by hand" process.  Tools like Pythonizer can only serve as the first stage, saving some efforts. This is a similar situation to Google translation from English to some German or, worse, Russian (or Polish or Ukranian). While trivial sentences are translated more or less correctly, there are many places where typically Google translation looks absurd or funny.

My "fuzzy pythonizer" project  perform some advanced "transliteration" of Perl to Python on statement levels taking into account limited context (like peephole optimization). The current quality can be seen in  Full protocol of translation of pre_pythonizer.pl by version 0.31 of pythonizer

After that "the devil is in details" and the main problem is that few people can muster two such complex languages to sufficient depths. So Stackoverflow and similar sites should be used to get the necessary information about particular construct and than you need to experiment with different variants, finding the most appropriate. 

Angle under which Python is presented in most textbooks and into books is usually quite different than the angle under which Perl programmer views the language. that means that for that task of translating a reasonably complex Perl script most books are of limited help.  What you need to do is to learn "in-depth" Python debugger so that you can see step by step how the constructs perform and there they what they are intended them to do.

If this is somebody else script that difficulties double, as you will not fully understand what the author intended  in Perl, to say nothing about Python. One of drawback of Perl programming culture is the cult of overcomplexity, the cult of clever idioms and it really hurts. While Perl language in many ways provide better clarity of expression then Python (and using sigils for scalar variable is actually a pretty good idea as that avoid any conflict with reserve words -- which is a problem for Python), many Perl scripts are difficult to read (and thus translate) not because of the quality of the language itself (which is pretty high, especially the quality of debugger -- which is higher than in Python) but perverse style of using it. In this sense activity of such "complexity addicts" as  Randal L. Schwartz  really hurt the language. Some Perl programmers values obscurity over clarity and pollute Perl code with bizarre idiomatic constructs, which supposedly demonstrate their cleverness, but only reveal their foolishness.  Those complexity junkies produced a lot of Perl code that can be found in standard modules. Here is one example of code from Perl standard library that extract options from the command line:

sub getopts
{
my ($argumentative,$hash)=@_;
my (@args,$first,$rest,$pos);
   @args = split( //, $argumentative );
   while(@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)$/s ){
      ($first,$rest) = ($1,$2);
      if (/^--$/) {	# early exit if --
         shift @ARGV;
         last;
      }
      ... ... ...
   }
Here a programmer less addicted to overcomplexity would write something like
while( scalar(@ARGV)>0 ){
   $cur_opt=$ARGV[0];
   $first=substr($cur_opt,0,1);
   last if( $first ne '-');
   if ($cur_opt eq '--'){
       shift @ARGV;
       last;
   }
   $rest=substr($cur_opt,1);
   ... ... ...
The latter code is so much easier to correctly translate into Python and it is more transparent and understandable.

Much also depends on subject area. Sysadmin scripts usually use very limited subset of Perl (almost always Perl 4 subset) and many of them can be translated almost perfectly.  They rarely use OO (which actually does not provide much value in this domain, anyway).  Funny thing during this process a lot of people, including myself develop strong allergy to Python. It is way too verbose, too many things are hidden in multiple obscure libraries and  and may constructs are archive enough , so the cheatsheet is needed, especially for functions   As a prototype you can use Perl to Python functions map

Python developers unstoppable itch to add yet another library makes language really baroque. Road to hell is always paved with good intentions. In a sense, Python repeated the blunder made in C++ on a new level: too much language functionality is "outsourced" into libraries. And that probably will affect viability and longevity of the language.   Of course, another factor that a seasoned Perl programmer  feels with  Python like a novice of skating ring :-)

With more complex staff, especially  Perl OO the return on investment in  automatic translation drops very quickly. In such cases Python script should use slightly or completely different logic then corresponding Perl script.  But again, if a Perl script being to specific narrow domain -- sysadmin scripts --- then  your chances are higher. Among areas that are esier to hangle are

In those case you can create some "conversion libraries" that simplify the task

So conversion means that you need to understand, document create set of tests and then rewrite the code.  For example, its rare in Perl to work character-by-character. Usually a lot of test processing is done using substr, index, split and regex. String in Python are immutable, so to imitate some Perl processing capabilities, for example using substr on the left side of the assignment statement (pseudo function) like in

substr($a,$start, $length)=$b;

you need first split the string into three parts and then reconstruct it replacing the middle part.

Perl's regex support is different and regex are better integrated with the language, so if advanced features are used, one-to-one translation is very difficult.  In simple cases translation is really straightforward and can be done automatically.  Please note that in Perl regex are often used for regular text processing, so they can be translated using text processing function of python without resorting to the use of regex library.

The quality of the results of syntax translation also depends on Perl coding style used and level of sophistication of programmer who initially wrote the script. Some Perl programmers are way too clever for their own good and resort to obscure idioms (look at Randal L. Schwartz books for inspiration ;-), which should probably be avoided in translation as kiss principle is a valid approach here.

When you analyze the logic of the script, often you discover some weak decisions, redundant parts, etc. This is especially typical for old scripts. So this work makes sense. 

Gotchas

Guido van Rossum was never a Unix specialist and it shows in Python interface with OS and I/O. As most of it was "outsourced" to libraries there are at least five or more solutions to each typical situation (for example, execute Unix command and get command output and return code). There is no consensus about what library to use not only between 2.7 and 3.x, but also within each Python version. C++ legacy was deliberately abandoned.

To understadn the lvel of balkanization of this area in Python one should just look at Stack Overflow posts on the topic. From them it clearly looks like a really shocking, dismal situation.

As Al Sweigart noted in his popular book Automate the Boring Stuff with Python, 2nd Edition

Python added the pathlib module in version 3.4. It's an alternative to the os.path modules that I just described. But why do we need another module?

In this sense Perl looks simpler and more consistent as I/O is a part of the language :-)

When we are talking about proliferation of modules/libraries Python key principle that supposedly distinguish it from Perl "There should be one -- and preferably only one -- obvious way to do it." looks like a nasty joke that is completely disconnected from the reality.

Python parser sometime marks as error perfectly legitimate constructs, for example

cur_nest=new_nest+=1

is not recognizes as a correct construct. Moreover, the absence of ++ operator lead to the fact that expression with increment and decrement operators like

$text[$n++]

do not have direct translation and increment need to be factored out before or after the statement depending whether this is prefix or postfix operation. Here Python tries to reinvent the wheel and, as typical in such cases fails, breaking compatibility with C and C++.

text[n]=''
n+=1
The information below is adapted from Perl 6 comparison, with corrections limiting it to Perl 5.

Blocks

In Python, indentation is used to indicate a block so { and } in Perl translated into indent in Python. This Fortran-style solution has its pluses and minuses. In a way you can view ":" as an equivalent of opening bracket in Perl, which makes the situation half less bizarre.

Python

if 1 == 2:
    print "Wait, what?"
else:
    print "1 is not 2." 

Perl

if( 1 == 2 ){
    say "Wait, what?"
} else {
    say "1 is not 2."
}
 

Parentheses are optional in both languages for expressions in conditionals, as shown above.

Variables

In Python, variables are declared and initialized at the same time. If variable first initialized within a subroutine, it gets a local scope, else a global scope. So the scope (local or global) is determined implicitly, based on the point in which the variable is initialized:

foo = 12
bar = 19

In Perl, the my declares a lexical variable. A variable can be initialized with =. This variable can either be declared first and later initialized or declared and initialized at once.

my $foo;       # declare
$foo = 12;     # initialize 
my $bar = 19;  # both at once

Also, as you may have noticed, variables in Perl usually start with sigils -- symbols indicating the type of their container. Variables starting with a $ hold scalars. Variables starting with an @ hold arrays, and variables starting with a % hold a hash (dict). Sigilless variables, declared with a \ but used without them, are bound to the value they are assigned to and are thus immutable.

Please note that, from now on, we are going to use sigilless variables in most examples just to illustrate the similarity with Python. That is technically correct, but in general we are going to use sigilless variables in places where their immutability (or independence of type, when they are used in signatures) is needed or needs to be highlighted.

Python

s = 10
L = [1, 2, 3]
d = { a : 12, b : 99 }
print s
print l[2]
print d['a']
# 10, 2, 12 

Perl

my $s = 10;
my @l = 1, 2, 3;
my %d = a => 12, b => 99;
my \x = 99;
say $s;
say @l[1];
say %d;  # or %d{'a'} 
say x;
# 10, 2, 12, 99

Scope

In Python, functions and classes create a new scope, but no other block constructor (e.g. loops, conditionals) creates a scope. In Python 2, list comprehensions do not create a new scope, but in Python 3, they do.

In Perl my variable belongs to the scope defined by curvy brackets in which it is encloses. Otherwise the variable is simply global

Python

if True:
    x = 10
print x
# x is now 10 

Perl

if True {
    my $x = 10
}
say $x
# error, $x is not declared in this scope  
my $x;
if True {
    $x = 10
}
say $x
# ok, $x is 10 

Python

x = 10
for x in 1, 2, 3:
   pass
print x
# x is 3 

Lambdas in Python can be written as blocks or pointy blocks in Perl.

Python

l = lambda i: i + 12
 

Perl

 
my $l = -> $i { $i + 12 }
 

Another Perl idiom for constructing lambdas is the Whatever star, *.

Perl

my $l = * + 12 # same as above

A * in an expression will become a placeholder for the argument, and transform the expression into a lambda at compile time. Each * in an expression is a separate positional parameter.

See the section below for more constructs regarding subroutines and blocks.

Another example (from the Python FAQ):

Python

squares = []
for x in range(5):
    squares.append(lambda: x ** 2)
print squares[2]()
print squares[4]()
# both 16 since there is only one x 
 

Perl

my \squares = [];
for ^5 -> \x {
    squares.append({ x≤ });
}
say squares[2]();
say squares[4]();
 
# 4, 16 since each loop iteration has a lexically scoped x,
 

Note that ^N is like range(N). Similarly, N..^M works like range(N, M) (a list from N to M - 1). The range N..M is a list from N to M. The ^ before or after the .. indicates that the beginning or ending endpoint of the list (or both) should be excluded.

Also, x≤ is a cute way of writing x ** 2 (which also works fine); the unicode superscript 2 squares a number. Many of the other unicode operators work as you would expect (exponents, fractions, π), but every unicode operator or symbol that can be used in Perl has an ASCII equivalent.

Loops

Python has for loops and while loops:

for i in 1, 2:

print i

j = 1

while j < 3:

print j

j += 1

 

# 1, 2, 1, 2

Perl also has for loops and while loops:

 
for 1, 2 -> $i {

say $i

}

my $j = 1;

while $j < 3 {

say $j;

$j += 1

}

 

(Perl also has a few more looping constructs: repeat...until, repeat...while, until, and loop.)

last leaves a loop in Perl, and is analogous to break in Python. continue in Python is next in Perl.

Python

 
for i in range(10):

if i == 3:

continue

if i == 5:

break

print i

 

 

Using if as a statement modifier (as above) is acceptable in Perl, even outside of a list comprehension.

The yield statement within a for loop in Python, which produces a generator, is like a gather/take construct in Perl. These both print 1, 2, 3.

Python

 
def count():

for i in 1, 2, 3:

yield i

for c in count():

print c

 

for count() -> $c {

say $c;

}
 

Lambdas, functions and subroutines

Declaring a function (subroutine) with def in Python is accomplished with sub in Perl.

 
def add(a, b):

return a + b

sub add(\a, \b) {

return a + b

}

 

The return is optional; the value of the last expression is used as the return value:

 
sub add(\a, \b) {

a + b

}
 
 
# using variables with sigils

sub add($a, $b) {

$a + $b

}

 

Python 2 functions can be called with positional arguments or keyword arguments. These are determined by the caller. In Python 3, some arguments may be "keyword only". In Perl, positional and named arguments are determined by the signature of the routine.

Python

 
def speak(word, times):

for i in range(times):

print word

speak('hi', 2)

speak(word='hi', times=2)
 

Perl

Positional parameters:

 
sub speak($word, $times) {

say $word for ^$times

}

speak('hi', 2);

 

Named parameters start with a colon:

 
sub speak(:$word, :$times) {

say $word for ^$times

}

speak(word => 'hi', times => 2);

speak(:word<hi>, :times<2>); # Alternative, more idiomatic
 

Perl supports multiple dispatch, so several signatures could be made available by declaring a routine as a multi.

 
multi sub speak($word, $times) {

say $word for ^$times

}

multi sub speak(:$word, :$times) {

speak($word, $times);

}

speak('hi', 2);

speak(:word<hi>, :times<2>);

 

Named parameters can be sent using a variety of formats:

 
sub hello {...};

# all the same

hello(name => 'world'); # fat arrow syntax

hello(:name('world')); # pair constructor

hello :name<world>; # <> quotes words and makes a list

my $name = 'world';

hello(:$name); # lexical var with the same name
 

Creating an anonymous function can be done with sub, with a block or with a pointy block.

Python

 
square = lambda x: x ** 2
 

Perl

 
my $square = sub ($x) { $x ** 2 }; # anonymous sub

my $square = -> $x { $x ** 2 }; # pointy block

my $square = { $^x ** 2 }; # placeholder variable

my $square = { $_ ** 2 }; # topic variable

 

Placeholder variables are lexicographically ordered to form positional parameters. Thus these are the same:

 
my $power = { $^x ** $^y };

my $power = -> $x, $y { $x ** $y };

 

Postfix statement modifiers

Postfix statement modifiers and blocks can be combined to easily create list comprehensions in Perl.

Python

 
print [ i * 2 for i in 3, 9 ] # OUTPUT: "[6, 18]␤"
 

Perl

 
say ( $_ * 2 for 3, 9 ); # OUTPUT: "(6 18)␤"

say ( { $^i * 2 } for 3, 9 ); # OUTPUT: "(6 18)␤"

say ( -> \i { i * 2 } for 3, 9 ); # OUTPUT: "(6 18)␤"
 

Conditionals can be applied, but the if keyword comes first, unlike in Python where the if comes second.

 
print [ x * 2 for x in 1, 2, 3 if x > 1 ] # OUTPUT: "[4, 6]␤"
 

vs

 
say ( $_ * 2 if $_ > 1 for 1, 2, 3 ); # OUTPUT: "(4 6)␤"
 

For nested loops, the cross product operator X will help:

 
print [ i + j for i in 3,9 for j in 2,10 ] # OUTPUT: "[5, 13, 11, 19]␤"
 

becomes either of these:

 
say ( { $_[0] + $_[1] } for (3,9) X (2,10) ); # OUTPUT: "(5 13 11 19)␤"

say ( -> (\i, \j) { i + j } for (3,9) X (2,10) ); # OUTPUT: "(5 13 11 19)␤"

say ( -> ($i, $j) { $i + $j } for (3,9) X (2,10) );# OUTPUT: "(5 13 11 19)␤"

say ( { $^a[0] + $^a[1] } for (3,9) X (2,10) ); # OUTPUT: "(5 13 11 19)␤"

 

Using map (which is just like Python's map) and grep (which is like Python's filter) is an alternative.

ß

Here's an example from the Python docs. First let's go over "instance variables" which are known as attributes in Perl:

Python:

 
class Dog:

def __init__(self, name):

self.name = name
 

Perl:

 
class Dog {

has $.name;

}
 

For each created class, Perl provides the constructor method new by default which takes named arguments.

Python:

 
d = Dog('Fido')

e = Dog('Buddy')

print d.name

print e.name

 

Perl

 
my $d = Dog.new(:name<Fido>); # or: Dog.new(name => 'Fido')

my $e = Dog.new(:name<Buddy>);

say $d.name;

say $e.name;

 

Class attributes in Perl can be declared in a few ways. One way is to just declare a lexical variable and a method for accessing it.

Python:

 
class Dog:

kind = 'canine' # class attribute

def __init__(self, name):

self.name = name # instance attribute

d = Dog('Fido')

e = Dog('Buddy')

print d.kind

print e.kind

print d.name

print e.name

 

Perl:

 
class Dog {

my $kind = 'canine'; # class attribute

method kind { $kind }

has $.name; # instance attribute

}

my $d = Dog.new(:name<Fido>);

my $e = Dog.new(:name<Buddy>);

say $d.kind;

say $e.kind;

say $d.name;

say $e.name;

 

In order to mutate attributes in Perl, you must use the is rw trait on the attributes:

Python:

 
class Dog:

def __init__(self, name):

self.name = name

d = Dog()

d.name = 'rover'
 

Perl:

 
class Dog {

has $.name is rw;

}

my $d = Dog.new;

$d.name = 'rover';
 

Inheritance is done using is:

Python

 
class Animal:

def jump(self):

print ("I am jumping")

class Dog(Animal):

pass

d = Dog()

d.jump()
 

Perl

 
class Animal {

method jump {

say "I am jumping"

}

}

class Dog is Animal {

}

my $d = Dog.new;

$d.jump;
 

Multiple inheritance is possible by using the is trait as many times as required. Alternatively, it can be used in conjunction with the also keyword.

Python

 
class Dog(Animal, Friend, Pet):

pass

 

Perl

 
class Animal {}; class Friend {}; class Pet {};

...;

class Dog is Animal is Friend is Pet {};
 

or

 
class Animal {}; class Friend {}; class Pet {};

...;

class Dog is Animal {

also is Friend;

also is Pet;

...

}
 

Decorators in Python are a way of wrapping a function in another one

Decorators in Python are a way of wrapping a function in another one. In Perl, this is done with wrap.

Python

 
def greeter(f):

def new():

print 'hello'

f()

return new

@greeter

def world():

print 'world'

world();
 

Perl

 
sub world {

say 'world'

}

&world.wrap(sub () {

say 'hello';

callsame;

});

world;

 

An alternative would be to use a trait:

 
# declare the trait 'greeter'

multi sub trait_mod:<is>(Routine $r, :$greeter) {

$r.wrap(sub {

say 'hello';

callsame;

})

}

sub world is greeter {

say 'world';

}

world;
 

Context managers in Python declare actions that happen when entering or exiting a scope

Context managers in Python declare actions that happen when entering or exiting a scope.

Here's a Python context manager that prints the strings 'hello', 'world', and 'bye'.

 
class hello:

def __exit__(self, type, value, traceback):

print 'bye'

def __enter__(self):

print 'hello'

with hello():

print 'world'

 

For "enter" and "exit" events, passing a block as an argument would be one option:

 
sub hello(Block $b) {

say 'hello';

$b();

say 'bye';

}

hello {

say 'world';

}
 

A related idea is 'Phasers' which may be set up to run on entering or leaving a block.

 
{

LEAVE say 'bye';

ENTER say 'hello';

say 'world';

}
 

I/O

In Python 3, the input keyword is used to prompt the user. This keyword can be provided with an optional argument which is written to standard output without a trailing newline:

user_input = input("Say hi → ")

print(user_input)

 

When prompted, you can enter Hi or any other string, which will be stored in the user_input variable. This is similar to prompt in Perl:

 
my $user_input = prompt("Say hi → ");

say $user_input; # OUTPUT: whatever you entered.


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Oct 22, 2019] Python for a Perl programmer

Oct 22, 2019 | stackoverflow.com

Ask Question Asked 9 years, 8 months ago Active 11 months ago Viewed 22k times 53 47


Hamish Grubijan ,Feb 17, 2010 at 17:56

I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others).

I might need to get some web work done in Python (most immediately, related to Google App Engine). As such, I'd like to ask SO overmind for good references on how to best learn Python for someone who's coming from Perl background (e.g. the emphasis would be on differences between the two and how to translate perl idiomatics into Python idiomatics, as opposed to generic Python references). Something also centered on Web development is even better. I'll take anything - articles, tutorials, books, sample apps?

Thanks!

FMc ,Dec 19, 2014 at 17:50

I've recently had to make a similar transition for work reasons, and it's been pretty painful. For better or worse, Python has a very different philosophy and way of working than Perl, and getting used to that can be frustrating. The things I've found most useful have been
  • Spend a few hours going through all the basics. I found the official tutorial quite good, if a little dry.
  • A good reference book to look up basic stuff ("how do I get the length of a string again?"). The ones I've found most useful are the Python Pocket Reference and Python Essential Reference .
  • Take a look at this handy Perl<->Python phrasebook (common tasks, side by side, in both languages).
  • A reference for the Python approach to "common tasks". I use the Python Cookbook .
  • An ipython terminal open at all times to test syntax, introspect object methods etc.
  • Get pip and easy-install (to install Python modules easily).
  • Learn about unit tests fast. This is because without use strict you will feel crippled, and you will make many elementary mistakes which will appear as runtime errors. I recommend nose rather than the unittest framework that comes with the core install. unittest is very verbose if you're used to Test::More .
  • Check out Python questions on Stack Overflow. In particular, Python - Things one MUST avoid and Python 2.x gotcha's and landmines are well worth a read.

Personally, I found Dive Into Python annoying and patronising, but it's freely available online, so you can form your own judgment on that.

Philip Durbin ,Feb 18, 2010 at 18:12

If you happen to be a fan of The Perl Cookbook , you might be interested in checking out PLEAC, the Programming Language Examples Alike Cookbook , specifically the section that shows the Perl Cookbook code translated into Python .

larley ,Feb 18, 2010 at 6:16

Being a hardcore Perl programmer, all I can say is DO NOT BUY O'Reilly's "Learning Python". It is nowhere NEAR as good as "Learning Perl", and there's no equivalent I know of to Larry Wall's "Programming Perl", which is simply unbeatable.

I've had the most success taking past Perl programs and translating them into Python, trying to make use of as many new techniques as possible.

Mike Graham ,Feb 17, 2010 at 18:02

Check out the official tutorial , which is actually pretty good. If you are interested in web development you should be ready at that point to jump right in to the documentation of the web framework you will be working with; Python has many to choose from, with zope, cherrypy, pylons, and werkzeug all having good reputations.

I would not try to search for things specifically meant to help you transition from Perl, which are not to be of as high of quality as references that can be useful for more people.

ghostdog74 ,Feb 18, 2010 at 1:17

This is the site you should really go to. There's a section called Getting Started which you should take a look. There are also recommendations on books. On top of that, you might also be interested in this on "idioms"

sateesh ,Feb 17, 2010 at 18:08

If what you are looking at is succinct, concise reference to python then the book Python Essential Reference might be helpful.

Robert P ,May 31, 2013 at 22:39

I wouldn't try to compare Perl and Python too much in order to learn Python, especially since you have working knowledge of other languages. If you are unfamiliar with OOP/Functional programming aspects and just looking to work procedurally like in Perl, start learning the Python language constructs / syntax and then do a couple examples. if you are making a switch to OO or functional style paradigms, I would read up on OO fundamentals first, then start on Python syntax and examples...so you have a sort of mental blueprint of how things can be constructed before you start working with the actual materials. this is just my humble opinion however..

[Oct 15, 2019] Perl to Python Function translation [closed]

Feb 01, 2014 | stackoverflow.com

Ask Question Asked 5 years, 8 months ago Active 5 years, 8 months ago Viewed 303 times -3


Jim Garrison ,Feb 1, 2014 at 22:24

I am trying to translate a Perl function into a Python function, but I am having trouble figuring out what some of the Perl to Python function equivalents.

Perl function:

sub reverse_hex {

 my $HEXDATE = shift;
 my @bytearry=();
 my $byte_cnt = 0;
 my $max_byte_cnt = 8;
 my $byte_offset = 0;
 while($byte_cnt < $max_byte_cnt) {
   my $tmp_str = substr($HEXDATE,$byte_offset,2);
    push(@bytearry,$tmp_str);
   $byte_cnt++;
   $byte_offset+=2;
 }
   return join('',reverse(@bytearry));
}

I am not sure what "push", "shift", and "substr" are doing here that would be the same in Python.

Any help will be much appreciated.

Kenosis ,Feb 1, 2014 at 22:17

The Perl subroutine seems rather complicated for what it does, viz., taking chunks of two chars at a time (the first 16 chars) from the sent string and then reverses it. Another Perl option is:
sub reverse_hex {
    return join '', reverse unpack 'A2' x 8, $_[0];
}

First, unpack here takes two characters at a time (eight times) and produces a list. That list is reverse d and join ed to produce the final string.

Here's a Python subroutine to accomplish this:

def reverse_hex(HEXDATE):
    hexVals = [HEXDATE[i:i + 2] for i in xrange(0, 16, 2)]
    reversedHexVals = hexVals[::-1]
    return ''.join(reversedHexVals)

The list comprehension produces eight elements of two characters each. [::-1] reverses the list's elements and the result is join ed and returned.

Hope this helps!

MikeMayer67 ,Feb 2, 2014 at 2:10

I realize that you are asking about the perl to python translation, but if you have any control over the perl, I would like to point out that this function is a lot more complicated than it needs to be.

The entire thing could be replaced with:

sub reverse_hex
{
  my $hexdate = shift;
  my @bytes = $hexdate =~ /../g;  # break $hexdate into array of character pairs
  return join '', reverse(@bytes);
}

Not only is this shorter, it is much easier to get your head around. Of course, if you have no control over the perl, you are stuck with what you were dealt.

Convert perl scripts to python with the awesome power of regular expressions

GitHub
pl2py.pl
#!perl -w
=head1 NAME
pl2py.pl
=head1 DESCRIPTION
Attempts to convert perl scripts to python with the awesome power of regular expressions.
=head1 BUGS
This will (probably) not actually produce runnable python files. But it saves a lot of work converting some perl to python.
More useful if your perl code is well-indented to start with (consider using a source formatter first).
=head1 AUTHOR
Daniel Perrett C<< dperrett@cambridge.org >>
=cut
my $state;
while (my $sLine = <>)
{
$sLine =~ tr/$//d;
$sLine =~ s/(?!<\d)\.(?!\d)/+/g;
$sLine =~ s/::/./g;
if ($state->{'pod'})
{
$sLine =~ s/^=(?!cut)//g;
}
elsif ($sLine =~ s/^=(?!cut)/"""/)
{
$state->{'pod'} = 1;
}
if ($sLine =~ s/^=cut/"""/)
{
$state->{'pod'} = 0;
}
$sLine =~ s/^\s*package (.*?);/class $1:/g;
$sLine =~ s/^\s*use /import /g;
$sLine =~ s/^\bundef\b/None/g;
$sLine =~ s/^\beq\b/==/g;
$sLine =~ s/^\bge\b/>=/g;
$sLine =~ s/^\ble\b/=</g;
$sLine =~ s/^\bne\b/!=/g;
$sLine =~ s/^\bgt\b/>/g;
$sLine =~ s/^\blt\b/</g;
$sLine =~ s/^\|\|/or/g;
$sLine =~ s/^&&/and/g;
$sLine =~ s/\s+{(['"])(.*)\1}/.$2/g;
#$sLine =~ s/^\s*sub\s*([\w]+)\s*(?:\(([^)]+)\))\s*\{?/def $1 ($2):/g;
$sLine =~ s/\bsub ([\w]+)(?:\(([^)]+)\))?\s*\{?/def $1:/g;
$sLine =~ s/\bmy ([\w]+)\s*=/$1 =/g;
$sLine =~ s/\bmy ([\w]+);//g;
$sLine =~ s/!/ not /g;
$sLine =~ s/->\{/./g;
$sLine =~ s/->\[/./g;
$sLine =~ s/->/./g;
$sLine =~ s/\{$/:/g;
$sLine =~ s/\}//g;
$sLine =~ s/;$//g;
print STDOUT $sLine;
}

geraldkrug commented on Sep 26

http://boughtupcom.scriptmania.com/cgi/perl2python.pl
perl to python cheatsheet

Converting perl to python - simple questions

ActiveState List Archives

In article <7fvagp$8lm$1 at nnrp1.dejanews.com>,
<sweeting at neuronet.com.my> wrote:

>>a) Perl's "defined".> [perl]> if (defined($x{$token})>> [python]> if (x.has_key(token) and x[token]!=None) :

That looks correct. Thankfully Python does have short-circuit evaluation. Note that if you normally expect x[token] to have a value,
you might restructure the code a bit to use try/except.

>b) RE's.> [perl]> if ($mytext !~ /^\s$/)>> [python]> if not (re.match('^\s$'), mytext)

I think you want

if not (re.match('^\s$', mytext)) :

or

if not (re.match('^\s*$', mytext)) :

(I think that Perl code has a bug in it by not including '*', but I could be wrong.)
--
--- Aahz (@netcom.com)

Hugs and backrubs -- I break Rule 6 <*> http://www.rahul.net/aahz/
Androgynous poly kinky vanilla queer het

From: Quinn Dunkan <qui...@necro.ugcs.caltech.edu>

25 Apr 1999 17:28:22 GMT

On Sun, 25 Apr 1999 15:51:29 GMT, Aahz Maruch <aahz at netcom.com> wrote:
>In article <7fvagp$8lm$1 at nnrp1.dejanews.com>,> <sweeting at neuronet.com.my> wrote:>>>>   [python]>>   if not (re.match('^\s$'), mytext)>>I think you want>>   if not (re.match('^\s$', mytext)) :>or>   if not (re.match('^\s*$', mytext)) :

Don't forget r'' in python when you have backslashes.

if not (re.match(r'^\s*$', mytext)):
From: Chad McDaniel <cha...@sgi.com>

26 Apr 1999 11:27:11 -0700

aahz at netcom.com (Aahz Maruch) writes:

> In article <7fvagp$8lm$1 at nnrp1.dejanews.com>,>  <sweeting at neuronet.com.my> wrote:> >> >a) Perl's "defined".> >   [perl]> >   if (defined($x{$token})> >> >   [python]> >   if (x.has_key(token) and x[token]!=None) :> > That looks correct.  Thankfully Python does have short-circuit> evaluation.  Note that if you normally expect x[token] to have a value,> you might restructure the code a bit to use try/except.> 

wouldn't x.get() work more elegantly:
---
if (x.get(token)) :
  [do stuff]
---


-- 
-chad
From: Florian Weimer <f...@cygnus.stuttgart.netsurf.de>

25 Apr 1999 19:07:14 +0200

sweeting at neuronet.com.my writes:

> a) Perl's "defined".>    [perl]>    if (defined($x{$token})> >    [python]>    if (x.has_key(token) and x[token]!=None) :

Depending on the code, you can omit the comparision to `None'.  Perl
programmers traditionally uses `defined' to test if a key is in a hash,
so your code is the correct translation if you mimic Perl's undefined
value with Python's `None', but most of the time, this is not required.

> b) RE's.>    [perl]>    if ($mytext !~ /^\s$/)> >    [python]>    if not (re.match('^\s$'), mytext)
                      
Your Python code unconditionally executes the `false' branch of the if statement.  I hope this is the correct translation:

	# Execute this once at the beginning of the program.
	single_space = re.compile(r'^\s$')  # use a r'aw' string

        # Later on, you can try to match this regexp to a string:
        if not single_space.match(mytext):

From: Andrew Johnson <andr...@home.com>

Sun, 25 Apr 1999 21:19:13 GMT

In article <m3u2u47hod.fsf at deneb.cygnus.stuttgart.netsurf.de>,
 Florian Weimer <fw at cygnus.stuttgart.netsurf.de> wrote:
! sweeting at neuronet.com.my writes:
! 
! > a) Perl's "defined".
! >    [perl]
! >    if (defined($x{$token})
! > 
! >    [python]
! >    if (x.has_key(token) and x[token]!=None) :
! 
! Depending on the code, you can omit the comparision to `None'.  Perl
! programmers traditionally uses `defined' to test if a key is in a hash,
! so your code is the correct translation if you mimic Perl's undefined
! value with Python's `None', but most of the time, this is not required.

Just a point of clarification: Actually, perl programmer's
traditionally use 'exists' to test if a key is in a hash ... using
'defined' to test for key existence is a mistake---'defined' will
only tell you if that key exists and has a defined value associated
with it: Witness the defined test on key2 in the following:

#!/usr/bin/perl -w
use strict;
my %hash = ( key1 => 0, 
             key2 => undef, 
             key3 => 1
           );
print "key1 exists\n"            if exists  $hash{key1};
print "key1 has defined value\n" if defined $hash{key1};
print "key1 has true value\n"    if $hash{key1};

print "key2 exists\n"            if exists  $hash{key2};
print "key2 has defined value\n" if defined $hash{key2};
print "key2 has true value\n"    if $hash{key2};

print "key3 exists\n"            if exists  $hash{key3};
print "key3 has defined value\n" if defined $hash{key3};
print "key3 has true value\n"    if $hash{key3};
__END__

which prints:
key1 exists
key1 has defined value
key2 exists
key3 exists
key3 has defined value
key3 has true value

regards
andrew

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

PerlPhrasebook - Python Wiki

https://leanpub.com/perl2python/read -- this is fragment of the book "Move Seamlessly between Perl and Python

crazy-compilers bridgekeeper -- A Perl to Python source code converter

Perthon -- Python to Perl Language Translation

How to best explain a "subtle" difference between Python and Perl ?
  • Perl Dictionary Convert
  • Python equivalent of Perl-ISAPI?
  • simple perl program in python gives errors
  • Python versus Perl
  • Python versus Perl ?
  • What is Python's answer to Perl?
  • Choosing Perl/Python for my particular niche
  • Need to convert an arbitrary byte-pair to an int.

    Browse more Python Questions on Bytes

    Python to Perl - nutshell

    https://github.com/lemay-ai/Pythonizer/blob/master/pythonizer.py

    Old limited syntax convertors



    Etc

    Society

    Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

    Quotes

    War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

    Bulletin:

    Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

    History:

    Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

    Classic books:

    The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Haterís Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

    Most popular humor pages:

    Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

    The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


    Copyright © 1996-2020 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) in the author free time and without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

    FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

    This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

    You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

    Disclaimer:

    The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

    Last modified: August, 22, 2020