Contents

Back to top

What variables mean

php | perl | perlr | python

....
k = key
v = value
i = numeric iterator
b = boolean
s = string
n = number
a = array
rx = regular expression
comment - best practice for language at top
Back to top

Booleans

php

true, false
Evaluates to false: 0,'',null,false,array() (empty array)
Everything else evaluates to true
case-insensitive. print true; will output '1', print false; will output ''

perl

0, '', undefined variables => all evaulate to false
1, everything else => all evaluate to true
there is no boolean datatype. print true; will output '1', print false; will output ''

python

True, False
Evaluates to false: False, None, '', 0, [], {}, ()
Everything else evaluates to true
names use initial caps

ruby

true,false - lowercase only
Evaluates to false: false, nil
Everything else evaluates to true, including 0, empty arrays and empty objects
Back to top

Null + other

php

null
case insensitive

perl

null
case insensitive

python

None
case sensitive

ruby

nil
Back to top

Division

php

10/3 = 3.333
behaves as you'd expect

python

10/3 # 3 - int/int is floored int
10/3.0 # 3.3333.. - int/float is standard float
10//3.0 # 3.0 int//float is floored float

ruby

10/3 # 3 - int/int is floored int
10/3.0 # 3.3333.. - int/float is standard float
10/3.to_f # 3.3333..
Back to top

Numeric power

php

$n = pow(2,3);

perl

$n = 2**3;

python

n = 2**3

python

n = pow(2,3)

ruby

n = 2**3
Back to top

Mod

php

$n = 4%3; // 1
$n = 4.5%3; // 1
#res = $n == 1.5;
converts arguments to integers

python

n = 4.5%3

ruby

n = 4.5%3
Back to top

For loop over an array

php

foreach($a as $v)
php5 can use &$v to create a reference

php

foreach($a as $i => $v)

php

for($i=0;$i<count($arr);$i++)

perl

for $v (@array)
including $v means that $_ won't be created

perl

for ($i=0;$i<=$#a;$i++) {
  $v = $a[$i];
}
$#a is the last position in the array, i.e. @a = (1,2,3); $#a == 2;

python

for i in a:
  v = a[i]

python

for v,i in zip(a,range(len(a))):

ruby

a.each do |v|

ruby

a.each_with_index do |v,i|

ruby

a.each{|v| v }
uses braces instead of do & end

javascript

for (var i=0;i<a.length;i++) {
  var v = a[i];
}
cannot use for (var v in a) because this will include .length
Back to top

For loop over a hash

php

foreach ($arr as $k => $v) {}
with key iterator

php

foreach ($arr as $v) {}

php

array_walk($h,create_function('&$v,$k','
  $v += 1;
'));
need to single quote strings else $var will get parsed

perl

for $k (keys %hash) {
  $v = $hash[$k];
}
including $k means that $_ won't be created

perl

for $s (%hash) {}
$s will output $k then $v, so is basically useless

python

for k in h:
  v = h[k]

ruby

h.each do |k,v|

javascript

for (var k in h) {
  var v = h[k];
}
Back to top

Statement modifiers slash tenary operators

php

$s = $b ? 'o' : 't';

perl

print 'hello' if 1;

python

s = 'o' if b else 't'

ruby

print 'hello' if true
x = x + 1 while x < 100
Back to top

Scalar construction

php

$s = 'abc';

perl

$s = 'abc';

python

s = 'abc'

ruby

s = 'abc'

javascript

var s = 'abc';
Back to top

Scalar referencing

php

$s2 = &$s;

perl

$s2 = \$s;
you need to deference $$v2 before you can do anything with it
Back to top

Scalar cloning

php

$v2 = $v;

perl

$v2 = $v;

python

v2 = v

ruby

v2 = v
Back to top

Trim

python

s2 = s.strip()
see http://docs.python.org/library/stdtypes.html#string-methods for more string methods, also http://en.wikibooks.org/wiki/Python_Programming/Strings

php

$s2 = trim($s);

perl

sub trim { $_[0] =~ /^\s*?(.*?)\s*$/; return $1; }
perl doesn't have a built in trim function
Back to top

Upper case string

php

$s2 = strtoupper($s);

python

s2 = s.upper()

perl

$s2 = uc($s);
Back to top

Lower case strimg

php

$s2 = strtolower($s);

python

s2 = s.lower()

perl

$s2 = lc($s);
Back to top

Upper case first letter of a string

python

s2 = s.capitalize()

perl

$s2 = ucfirst($s);
use lcfirst for the opposite

perl

$s2 = ucfirst($s);
use lcfirst for the opposite - this is identical to php
Back to top

Upper case first letter of each word - i.e. like excel proper()

php

$s2 = ucwords($s);

python

s2 = s.title()
Back to top

Array construction

php

$a = array(1,2,3);

python

arr = [1,2,3]

perl

@arr = (1,2,3);
arrays can only be single dimensional, unless you use references

perlr

$arr_ref = [1,2,3];

perl

@arr = qw(cat dog fish);
unquoted, so no spaces

ruby

a = [1,2,3]

ruby

a = %w[cat dog fish]
unquoted, so no spaces
Back to top

Array cloning

php

$a2 = $a;

perl

@a2 = @a;

python

a2 = a[:]
non-scalers within array will be copied as references. Does the same thing as copy.copy()

python

import copy
a2 = copy.deepcopy(a)
non-scalers within array will be cloned as new objects

ruby

a2 = a.clone
non-scalers within array will be copied as references
Back to top

Array referencing

php

$a2 = $a;

python

a2 = a

ruby

a2 = a
Back to top

Hash construction with values

php

$h = array('k'=>'v','k2'=>'v2');

perl

%h = ('k','v','k2','v2');
hashs can only be single dimensional, unless you use references

perlr

$h_ref = {k => 'v', k2 => 'v2'};

python

h = {'k':'v','k2':'v2'}

ruby

h = {'k'=>'v','k2'=>'v2'}
Back to top

Hash add key / value

php

$a[$k] = $v;

perl

$hash{$k} = $v;
use $hash rather then %hash, because the value you are refering to is a scalar

perlr

$hash->{$key};

python

h[k] = v

ruby

h[k] = v
Back to top

Hash cloning

php

$h2 = $h;

perl

%h2 = %h;

python

h2 = h.copy()
Back to top

Hash referencing

php

$h2 = &$h;

python

h2 = h
Back to top

Create a range

php

$a = range(0,5);
inclusive, i.e. 0,1,2,3,4,5

perl

@a = 1..5;
also works with letters i.e. a..j

ruby

r = 0..2 # 0,1,2
r = 0...2 # 0,1
a range in an object in ruby, not an array
Back to top

Array push

php

$a[] = $v;

php

array_push($a,$v);

perl

push $a, $v;

python

arr.append(v)

ruby

a.push v

ruby

a << v
Back to top

Array pop

php

$v = array_pop($arr);

perl

$v = pop @a;

python

v = a.pop()

ruby

v = a.pop
Back to top

Array access last value

php

$v = $a[count($a)-1];

php

$v = end($a)
moves internal array pointer which may mess up looping

perl

$v = $a[-1];

python

v = a[-1]

ruby

v = a[-1]
Back to top

Array access single value

php

$v = $a[1];

perl

$v = $arr[5];

perlr

$v = $arr->[5];

python

v = a[1]

ruby

v = a[1]
Back to top

Array access multiple values

perl

@a2 = @a[1,3];
returns 1 AND 3

python

a2 = a[1::2]
starting at 1, access every 2nd value

ruby

a2 = a[2..4]
return values 2 to 4 inclusive. can also been used to set values i.e. a[2..4] = [7,8,9]

ruby

a2 = a[2...4]
return values 2 to 4 exclusive
Back to top

Array modify value

php

$arr[5] = 10;

python

arr[5] = 10;

perl /* using $arr[5] because $v is a scaler, you don't use @arr[5] as you'd expect

$arr[5] = 10;

perlr

$arr->[5] = 10;
Back to top

Value exists in array

php

$b = in_array($v,$a);

perl

$v = grep $_ eq $v, @arr
returns $v if it finds it (which will always be evaluated as 'true' even if $v is 0

perl

$v = grep $v, @a;
though didn't work when was looking up IP addy for key

python

b = v in a

ruby

b = a.include? v
Back to top

Array comparison

ruby

b = a == a2
Back to top

Array length

php

n = count(a);

perl

$n = scalar @a;

ruby

n = a.length
a.size is an alias

ruby

n = a.nitems
doesn't include nil values
Back to top

Array sort

php

function _sort($a,$b) { return strcasecmp($a,$b); }
usort($a,'_sort');
sorts in place. _sort returns <0, 0 or >0;

php

usort($a, create_function('$a,$b','return strcasecmp($a,$b);'));
lamba style - however these don't get garbage collected so if this is in a look it'll create a mess

python

a.sort()
sorts in place

ruby

a2 = a.sort

ruby

a.sort!
sort in place

ruby

a2 = a.sort {|x,y| a <=> b}
<=> is comparison operator, returns -1, 0, 1
Back to top

Hash sort

php

ksort
uksort
see array sort

python

a = h.keys()
a.sort()
for k in a:
  v = h[k]
hashes are naturally unordered in python
Back to top

Key exists in hash

php

$b = isset($h[$k]);

perl

$b = defined $arr[$k];

python

b = a.has_key(k)

ruby

b = h.include? k
Back to top

Hash keys

php

$a = array_keys($h);

perl

@a = keys %h;

python

a = h.keys()
Back to top

Hash values

php

$a = array_values($h);

perl

$a = values %h;
Back to top

String concatination

php

$s = 'a' . 'b';

perl

$s = 'a' . 'b';

python

s = 'a' + 'b'

ruby

s = 'a' + 'b'
Back to top

Charcode

php

$s = chr($n);

perl

$s = chr($n);

ruby

dunno :-)
Back to top

String replace

php

$s = str_replace(match, replacement, $s);

python

s2 = s.replace(match, replacement)
Back to top

Utf print

python

import codecs
sys.stdout = codecs.getwriter('utf')(sys.stdout) # sometimes you'll need this
Back to top

Sprintf

php

$s = sprintf('The %s brown %s','quick','fox');

perl

$s = sprintf('The %s brown %s','quick','fox');

python /* can use a scaler instead of an tuple if only a single value */

s = 'The %s brown %s' % ('quick','fox')
Back to top

String to array - split

php

$arr = preg_split("/$rx_delimeter/",$s);

php

$arr = split($delimeter,$s);

php

$arr = explode($delimeter,$s);
identical to split?

perl

@a = split /$rx/, $s;
can also just use $s instead of /$rx/
Back to top

Array to string - join

php

$s = implode($glue, $a);

python

s = ''.join(a)
Back to top

Regular expression match

php

$b = preg_match("/$rx/",$s);
can use other delimiters

php

preg_match_all("/$rx/",$s,$matches);
will save details of matches to array $matches

perl

$b = $s =~ /$rx/;

perl

$b = $s =~ m{$rx}; # or () <> || ## etc
$s = 'abc';
$rx = 'b';
$rx2 = 'd';
$res = $s =~ m{$rx} and not $s =~ m($rx2);
allows different delimiters including braces + brakets. standard // is actually just a shortcut for m//

ruby

n = s =~ /rx/
returns the character offset of match, nil if no match

ruby

n = s =~ /#{rx}/
dynamic
Back to top

Regular expression replace

php

$s = preg_replace("/$rx/",$replacement,$s);

perl

$s =~ s/$rx/$replacement/g;

python

import re
$s = re.sub(rx,replacment,s)
make rx strings with "r" i.e. r'c:\user'. use matches in replacement like r'\1hello\2'
Back to top

Array slice

php /* unknown */

$a = array_slice()

perl

@a2 = @a[1..3];
returns 1 TO 3

python

a2 = a[1:3]
returns 1 TO 2, i.e. 1 - (not including) 3
Back to top

Array reverse

php

$a2 = array_reverse($a);

perl

@a2 = reverse @a;

python

a.reverse()
reserves in place
Back to top

Iterate line by line over a text file

php

$fh = fopen('data.txt');
while ($line = fgets($fh)) {
  $line = preg_replace('/[\r\n]/','',$line);
}
fclose($fh);

php

$s = file_get_contents('data.txt');
$arr = preg_split('/\n/',$s);
foreach ($arr as $line) ...
will read entire file into memory first

perl

open FH, 'data.txt';
for $line (<FH>) {
  chomp $line;
}
close FH;
or can for (<FH>) and $line = $_

python

sys.stdout = codecs.getwriter('utf')(sys.stdout) # so that you can use the 'print' fn
import codecs
fh = codecs.open(filename,'r','latin-1')
for line in fh:
in python its critical that you use codecs to open files so that any non ascii characters get happily encoded in unicode /* i think */

python

fh = open(filename,'r')
for line in fh:
will result in a string object rather then a unicode object. this can cause big headaches if it includes non ascii characters /* i think */
Back to top

Write to a file

php

$fh = fopen('out.txt','w');
fwrite($fh,$s);
fclose($fh);

perl

open FH, '>out.txt';
print FH "Hello world\n";
close FH;
use > for write, >> for append

python

f = open('out.txt', 'w')
f.write(s)
f.close()
Back to top

Read contents from an external website

php

$s = file_get_contents($url);
download a library that implements cURL for anything more advanced using HTTP

python

import httplib
conn = httplib.HTTPConnection('www.somewhere.net.nz')
conn.request("GET", "/documents/index.html")
xhtml = conn.getresponse().read()
Back to top

Call a system command, get output

php

ob_start();
system($command);
$s = ob_get_clean();
print $s;
Back to top

Get arguments after calling from command line

php

$argv;

perl

@ARGV;
refer to them as $ARGV[0] etc

python

sys.argv;
Back to top

Cgi - get

php

$h = $_GET;
Back to top

Cgi - post

php

$h = $_POST;
there's also a way to get raw post, something like apache_request_headers(':/POST');
Back to top

While loop

php /* don't think that it uses the word 'do' anywhere */

while ($b) {}

perl

while ($b) {}
Back to top

Do loop

perl

do {} while ($b);
Back to top

Switch statement

php

switch ($var) {
  case 'one': // is in $var == 'one'
  default:
}
*i think*
Back to top

Continue, break

php

foreach ($a as $v) {
  if ($b) continue;
  # do whatever
}
break acts exactly the same

perl

NAMED_LINE: for ($i=0;$i<scalar(@a); $i+=1) {
  next NAMED_LINE if ($i >= 5);
}
Equivalent of continue, not sure what to do for break

python

for i in range(len(a)):
  if i >= 5: continue
break acts exactly the same
Back to top

Else if

php

else if
elseif
either is fine

python

elif

perl

elsif
Back to top

Deleting varaiables

php

unset($var);

python

del var;
Back to top

php

print_r($arr);
var_dump($var);

perl

use Data::Dumper;
print Dumper \$var;

perl

use Data::Dumper;
sub p { print $_[0].chr(10); }
sub d { print Dumper @_; }
Back to top

Mysql datetime to timestamp - 2008-10-14 12:00:04

php

$val = explode(" ",$datetime);
$date = explode("-",$val[0]);
$time = explode(":",$val[1]);
$timestamp = mktime($time[0],$time[1],$time[2],$date[1],$date[2],$date[0]);
Back to top

Open a mysql database connection

php

$db = mysql_connect($host,$username,$password);
mysql_select_db($database);

python

import MySQLdb, MySQLdb.cursors
db_connection = MySQLdb.connect(user=username, passwd=password, db=database , cursorclass=MySQLdb.cursors.DictCursor)
db = db_connection.cursor()
db.close() at end of script
Back to top

Mysql query return assoc

php

$result = mysql_query($sql);
while ($row = mysql_assoc($result))

python

db.execute(sql)
db.fetchall()

python

db.execute(sql)
db.fetchone()
Back to top

Mysql insert

php

mysql_query($sql);

python

db.execute(sql)
db_connection.commit()
Back to top

Die / exit

php

die($s);

php /* i think */

exit($s);

perl

die($s);

perl

exit();

python

import sys
sys.exit()
Back to top

Loop a filesystem directory

perl

sub loop_dir_recursive {
  my ($dir) = $_[0];
  for my $filepath(<$dir/*>) {
  $filename = $filepath;
  $filename =~ s|^.*/(.*)$|$1|g; # switch slash around for windows
  if (-d $filepath) {
  # is a directory
  loop_dir_recursive($filepath);
  } elsif (-f $filepath) {
  # is a file
  } else {
  # is something else ie symlink
  }
  }
}
Back to top

Recursively copy a directory with file filter

perl

use File::Copy 'cp';
use File::Path 'mkpath';
sub copy_files_recursive {
  my ($dir) = @_;
  for my $filepath (<$dir/*>) {
  if (-d $filepath) {
  next if ($filepath =~ m!(output|rips)!);
  copy_files_recursive($filepath);
  } elsif (-f $filepath) {
  if ($filepath =~ m!\.(png|gif|jpg)$!) {
  $target_filepath = 'output/test/' . $filepath;
  $target_path = $target_filepath;
  $target_path =~ s!/[^/]*?$!!g;
  if (not -e $target_path) {
  mkpath($target_path) or die ("$!");
  print "Creating $target_path".chr(10);
  }
  print "Copying $filepath -> $target_filepath".chr(10);
  cp $filepath, $target_filepath or die ("$!");;
  }
  } else {
  # is something else ie symlink
  }
  }
}
Back to top

Class

php

class MyClass extends MyParent {
  var $my_var = 15;
  function MyClass($arg) { // constructor - __construct for php5 ??
  $this->MyParent($arg); // super
  }
}

python

class MyClass(MyParent):
  my_var = 15
  def __init__(self): # constructor
  self.my_other_var = 17

ruby

class Child < Parent
  my_var :my_val
  attr_accessor :instance_var # writes getter + setter
  def initialize(v)
  @instance_var = v
  end
  def self.class_method
  end
  protected
  def pro
  end
  private
  def priv
  end
end
Back to top

Construct object

php

$my_obj = new MyClass($arg);

python

my_obj = MyClass(arg)
Back to top

Dynamic variable

php

${$var}
Back to top

Dynamic function

php

call_user_func($fn,$args);
Back to top

Import

php

require()
require_once()
include()
include_once
require will throw an error of some kind - *i think* that saying _once() means that it won't import if asked to import multiple times, so no need to check if a class already exists

perl

use Data::Dumper;
this uses stuff from CPAN etc, think there's a different syntax for getting stuff that's local and relative to .pl file
Back to top

Define a constant

php

define('MY_CONST', 64);
Back to top

Escape html to display in a browser

php

$s = htmlentities($s);
Back to top

Escape string for database use

php /* i think */

$s = mysql_real_escape_string($s);
Back to top

Encode a string in windows-1251 (though is this ever actually used even if charset is specified in html?)

Back to top

Encode a string in iso-8859-1 (latin-1)

Back to top

Encode a string in utf

Back to top