Contents
- Introduction
- The obvious
- The not so obvious
- Simple types
- Importing
- Common tasks
- Some general comparisons
-
Lists of lists
- Lists of lists: preliminaries
- requires/imports
- Declaration of a list of lists
- Generation of a list of lists
- Filling a list of lists with function calls
- Filling a list of lists with function calls, using temporaries
- Adding to an existing row in a list of lists
- Accessing elements of a list of lists
- Printing a list of lists
- Hashes/dictionaries of lists
- Lists of hashes/dictionaries
- Interface to the Tk GUI toolkit
Introduction
This phrasebook contains a collection of idioms, various ways of accomplishing common tasks, tricks and useful things to know, in Perl and Python side-by-side. I hope this will be useful for people switching from Perl to Python, and for people deciding which to choose. The first part of the phrasebook is based on Tom Christiansen's Perl Data Structures Cookbook.
I have only been working on this for a short time, so many of the translations could probably be improved, and the format could be greatly cleaned up.
I will get the data-structures cookbook translated first and then go back to clean up the code. Also, since I have been using Python for far less time than Perl, there are certainly idioms I don't know or that I will misuse. Please feel free to fix and update.
--
Other references: PLEAC.
--
Thanks to David Ascher, Guido van Rossum, Tom Christiansen, Larry Wall and Eric Daniel for helpful comments.
--
TODO:
- break up into multiple smaller pages
- use modern Python idioms
- use modern Perl idioms
- add more points of comparison
- Use sorted() where appropriate
- Get rid of map() where possible.
- Simple types (strings, lists, dictionaries, etc.)
- Common tasks (reading from a file, exception handling, splitting strings, regular expression manipulation, etc.)
- Sections 4 and 5 of the Perl Data Structures Cookbook.
- Vertical whitespace needs fixing.
QUESTIONS:
- Should function and data structure names for python code be in python_style (and more appropriate/informative)?
The obvious
Python don't need no steenking semicolons.
The not so obvious
There are many Integrated Development Environments, (IDEs), for Python that are usually recommended to new users and used by seasoned Python programmers alike. The Idle IDE is a TK based GUI providing language-aware editing, debugging and command line shell for Python that is part of the Python distribution. Many of the python examples shown can be experimented with in the Idle IDE.
Simple types
Strings
Creating a string
$s = 'a string';
s = 'a string'
The $ in Perl indicates a scalar variable, which may hold a string, a number, or a reference. There's no such thing as a string variable in Python, where variables may only hold references.
- You can program in a Pythonesque subset of Perl by restricting yourself to scalar variables and references. The main difference is that Perl doesn't do implicit dereferencing like Python does.
Quoting
$s1 = "some string";
$s2 = "a string with\ncontrol characters\n";
$s3 = 'a "quoted" string';
$s4 = "a 'quoted' string";
$s5 = qq/a string with '" both kinds of quotes/;
$s6 = "another string with '\" both kinds of quotes";
$s7 = 'a stri\ng that au\tomatically escapes backslashes';
foreach my $i ($s1, $s2, $s3, $s4, $s5, $s6, $s7)
{
print "$i\n";
}s1 = "some string" s2 = "a string with\ncontrol characters\n" s3 = 'a "quoted" string' s4 = "a 'quoted' string" s5 = '''a string with '" both kinds of quotes''' s6 = "another string with '\" both kinds of quotes" s7 = r"a stri\ng that au\tomatically escapes backslashes" for i in (s1, s2, s3, s4, s5, s6, s7): print(i)
In both languages, strings can be single-quoted or double-quoted. In Python, there is no difference between the two except that in single- quoted strings double-quotes need not be escaped by doubling them, and vice versa. In Perl, double-quoted strings have control characters and variables interpolated inside them (see below) and single-quoted strings do not.
Both languages provide other quoting mechanisms; Python uses triple quotes (single or double, makes no difference) for multi-line strings; Python has the r prefix (r"some string" or r'some string' or r"""some string""" or r'''some string''') to indicate strings in which backslash is automatically escaped -- highly useful for regular expressions. Perl has very elaborate (and very useful) quoting mechanisms; see the operators q, qq, qw, qx, etc. in the PerlManual.
Quoting is definitely one of the areas where Perl excels.
Note that in Perl you can always replace foreach with for, which is shorter; but explicitly writing foreach is clearer, so you don't confuse it with the other kind of for.
Interpolation
$name = "Fred"; $header1 = "Dear $name,"; $title = "Dr."; $header2 = "Dear $title $name,"; print "$header1\n$header2\n";
name = "Fred"
header1 = f"Dear {name},"
title = 'Dr.'
header2 = f'Dear {title} {name},' # Single quote f-strings also interpolate.
print(f"{header1}\n{header2}") # Don't need final \n.Perl's interpolation is slightly more convenient (don't need a special string modifier), though slightly less powerful than Python's % operator. Remember that in Perl variables are interpolated within double-quoted strings, but not single-quoted strings.
Perl has a function sprintf that uses the % conversion á la C; so the above lines could have been written:
$name = "Fred"; $header1 = sprintf "Dear %s,", $name; $title = "Dr."; $header2 = sprintf "Dear %s %s,", $name, $title;
Python's % (format) operator is generally the way to go when you have more than minimal string formatting to do (you can use + for concatenation, and [:] for slicing). It has three forms. In the first, there is a single % specifier in the string; the specifiers are roughly those of C's sprintf. The right-hand side of the format operator specifies the value to be used at that point:
x = 1.0/3.0 s = 'the value of x is roughly %.4f' % x
If you have several specifiers, you give the values in a list on the right hand side:
x = 1.0/3.0 y = 1.0/4.0 s = 'the value of x,y is roughly %.4f,%.4f' % (x, y)
Finally, you can give a name and a format specifier:
x = 1.0/3.0 y = 1.0/4.0 s = 'the value of x,y is roughly %(x).4f,%(y).4f' % vars()
The name in parentheses is used as a key into the dictionary you provide on the right-hand side; its value is formatted according to the specifier following the parentheses. Some useful dictionaries are locals() (the local symbol table), globals() (the global symbol table), and vars() (equivalent to locals() except when an argument is given, in which case it returns arg.__dict__).
PEP215 proposed a $"$var" substitution mode as an alternative to "%(var)s" % locals(), but was rejected in favour of the explicit Template class proposed in PEP292, which required no syntax changes.
Modifying a string
$s1 = "new string"; # change to new string $s2 = "new\nstring\with\nnew\nlines"; # change to new string $s2 =~ s/\n/[newline]/g; # substitute newlines with the text "[newline]" $s2 = substr $s2, 0, 3,''; # extract the first 3 chars: "new" print "$s1\n$s2\n";
s1 = "new string" # change to new string
# substitute newlines with the text "[newline]"
s2 = s2.replace("\n", "[newline]")
s2 = s2[:3]
print(f"{s1}\n{s2}")In Perl, strings are mutable; the third assignment modifies s2. In Python, strings are immutable, so you have to do this operation a little differently, by slicing the string into the appropriate pieces.
A Python string is just an array of characters, so all of the array operations are applicable to strings. In particular, if a is an array, a[x:y] is the slice of a from index x up to, but not including, index y. If x is omitted, the slice starts at the beginning of the array; if y is omitted, the slice ends at the last element. If either index is negative, the length of the array is added to it. So a[-4:] is the last four characters of a.
In Perl, slicing is performed by giving the array a list of indices to be included in the slice. This list can be any arbitrary list and by using the range operator ..., you can get Python like slicing. If any of the indices in the list is out of bounds an undef is inserted there.
@array = ('zero', 'one', 'two', 'three', 'four')
# slicing with range operator to generate slice index list
@slice = @array[0..2] # returns ('zero', 'one', 'two')
# Using arbitary index lists
@slice = @array[0,3,2] # returns ('zero', 'three', 'two')
@slice = @array[0,9,1] # returns ('zero', undef, 'one')Note: Perl range operator uses a closed interval. To get the range to the end of the array, the last index must be used as
@a=(1,2,3,4,5); $#a; # last index, 4, because the firs index is 0 as in Python. @a[ 2..$#a ] # as Python's a[2:]
Importing
In Perl a module is simply a package with a package name. ( see: perldoc -f package ). The symbols exported by the module depends on the module itself. The module may export symbols - mostly functions - by default, on request or none of them. In the latter case the module usually a class or has special access, like File::Spec. In Perl the module interfaces may vary - see the doc of the particular module.
use Module; # imports module. It module exports symbols by default, those appeare in the package namespace. use Module qw(symbol1 symbol2 symbol3); # preferred or use Module "symbol1";
from module import symbol1, symbol2, symbol3 # Allows mysymbol.func() from module import symbol1 as mysymbol # Unless the module is specifically designed for this kind of import, don't use it from module import * module.func()
Common tasks
Reading a file as a list of lines
my $filename = "cooktest1.1-1"; open my $f, $filename or die "can't open $filename: $!\n"; @lines = <$f>;
filename = "cooktest1.1-1"
f = open(filename) # Python has exceptions with somewhat-easy to
# understand error messages. If the file could
# not be opened, it would say "No such file or
# directory: %filename" which is as
# understandable as "can't open $filename:"
lines = f.readlines()In Perl, variables are always preceded by a symbol that indicates their type. A $ indicates a simple type (number, string or reference), an @ indicates an array, a % indicates a hash (dictionary).
In Python, objects must be initialized before they are used, and the initialization determines the type. For example, a = [] creates an empty array a, d = {} creates an empty dictionary.
