python for perl programmers

Matt Biddulph

BBC

http://www.hackdiary.com

the programmers

They run around like big slobbering St Bernards, knocking over the quietly studious Python guys and barging into the BOFs, barking and licking people whenever they find them.
-- Danny O'Brien on the perl guys at OSCON 2003
People don't learn Python because it will get them a job; they learn it because they genuinely like to program and aren't satisfied with the languages they already know.
-- Paul Graham

creator of perl

creator of python

syntax

types

scalar int, float, str, etc.
array list
hash dict

Because native types are objects, they all work with the same operators, so there's no == versus eq distinction. But this means that 1 != "1" because an int can't equal a str. Of course, str(1) == "1".

loops

foreach my $item (@array) { 
  print $item."\n"; 
}
for item in array:
  print item

but in python the same syntax works for dictionaries:

foreach my $key (keys %hash) { 
  print $key."\n"; 
}
for key in hash:
  print key

and in fact for anything that can be iterated over, such as strings:

foreach my $character (split(//,$string) { 
  print $character."\n"; 
}
for character in string:
  print character

regexps

Regexp syntax the same as perl, but used with OO syntax:

$x = "foo";
$x =~ s/oo/ee/g;
import re
x = "foo"
x = re.sub("oo","ee",x)

$x = "foo";
@matches = ($x =~ /(o)/g);
if(scalar @matches) {
  print $matches[0]."\n";
}
import re
x = "foo"
results = re.search("(o)",x)
if results is not None:
  print results.group(1)

Python's object orientation

Pretty much everything's an object, including classes and native types:

>>> x = [1,2,3,2]
>>> print x.count(2)
2
>>> x.append(4)
>>> print x
[1,2,3,2,4]

So your classes can subclass builtin types

class MyString(str):
    def foo(self):
        return "foo"
        # MyStrings behave like strings but have a foo() method too

Python's object orientation

Many things you'd find in man perlfunc are methods on builtin types:

exceptions

In perl, if something should work, it mostly does:

> print 1 + "1"
2

Python distinguishes between types of scalars (numbers, strings, etc) more rigidly:

>>> print 1 + "1"
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Python has exceptions, so you can still write a block of code that might blow up without having to explicitly check for failures:

try:
  print 1 + "1"
  print "Well, that went fine"
except TypeError:
  print "I can't add up strings and integers, sorry."

gotchas

fun things

cheers!