[Tutor] Translating a Perl script into Python

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 20 Jan 2001 01:56:30 -0800 (PST)


On Fri, 19 Jan 2001, Sheila King wrote:

> As part of my learning exercises, I've been attempting to translate a short
> perl script into Python.

Let's take a look at one particular line:

> @qmail = qw(SENDER NEWSENDER RECIPIENT USER HOME HOST LOCAL EXT EXT2 EXT3
> EXT4 DTLINE RPLINE UFLINE);

> qmail = ["SENDER", "NEWSENDER", "RECIPIENT", "USER", "HOME", "HOST", "LOCAL",
> "EXT", "EXT2", "EXT3", "EXT4", "DTLINE", "RPLINE", "UFLINE"]

You could also write that as:

    qmail = "SENDER NEWSENDER RECIPIENT USER HOME HOST LOCAL EXT\
             EXT2 EXT3 EXT4 DTLINE RPLINE UFLINE".split()

String methods are fun!  I think this is close to the spirit of Perl's
qw() "quoteword" function.  If you don't have Python 2.0, then calling
string.split() on the string will have the same effect.


Let's look at another part of the program:

    @slurp = <>;
    # [some stuff cut]
    print PROC @slurp;

versus:

    slurp = sys.stdin.read()
    # [some stuff cut]
    for line in slurp:
        PROC.write(line)

This isn't quite equivalent because the Perl code is printing lines at a
time, but the Python code is printing single characters at a time.  We get
the same effect eventually, but it's not as direct as:

    PROC.write(slurp)

Just write thatwhole string out, since slurp already has those newlines
embedded into it.  The distinction makes more sense with a small
interpreter session:

###
>>> mystr = "test\nme"
>>> for ch in mystr: print ch      # commentary: iteration over chars
... 
t
e
s
t


m
e
>>> from sys import stdout
>>> for ch in mystr: stdout.write(ch)
...                    # same thing, but hidden by write()'s behavior
test
me>>> print mystr
test
me
>>> stdout.write(mystr)  # almost the same, and easier to understand
test
me>>> 
###


Strings are sequences --- that is, you can go through each character with
a for-loop.  In your code above, though, this is probably not what you
wanted.

Hope this helps!