Contents

Back to top

What variables mean (change title)

php | perl | perlr | python

....
k = key
v = value
i = numeric iterator
b = boolean
s = string
n = number
arr = array
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
Back to top

Null + other

php

null
case insensitive

perl

null
case insensitive

python

None (null)
Back to top

Division

python

10/3 #int/int is floored
10/3.0 #int/dbl is standard
10//30 #int//dbl is floored:
Back to top

Numeric power

php

$n = pow(2,3);

perl

$n = 2**3;

python

n = 2**3

python

n = pow(2,3)
Back to top

Mod

php

$n = 4.5%3;
$n = 4.5%3;
#res = $n == 1.5;

python

n = 4.5%3
Back to top

For loop over an array

php

foreach($a as $v)

php

foreach($a as $i => $v)
also create a numeric iterator

php

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

perl

for $v (@array)
including $k 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]
Back to top

For loop over a hash

php

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

php

foreach ($arr as $v)

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
Back to top

Backwards if

perl

print 'backwards' if true;
Back to top

Scalar construction

php

$s = 'abc';

perl

$s = 'abc';

python

s = 'abc'
Back to top

Scalar referencing

perl

see comments
$v2 = \$v; referencing it but 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
Back to top

Array construction

php

$arr = 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
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
Back to top

Array referencing

php

$a2 = $a;

python

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'}
Back to top

Hash add key / value

php

$arr[$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
Back to top

Hash cloning

php

$h2 = $h;

perl

%h2 = %h;

python

h2 = h.copy()
Back to top

Hash referencing

php

$h2 = &$h;

perl

1

python

h2 = h
Back to top

Create a range

php

$a = range(0,5);

perl

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

Array push

php

$arr[] = $v;

php

array_push($arr,$v);

python

arr.append(v)

perl

push $a, $v;
Back to top

Array pop

php

$v = array_pop($arr);

perl

$v = pop @a;

python

v = a.pop()
Back to top

Array access last value

php

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

perl

$v = $a[-1];

python

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]
Back to top

Array access multiple values

perl

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

python

a[1::2]
starting at 1, access every 2nd value
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
Back to top

Key exists in hash

php

$b = isset($arr[$k])

perl

$b = defined $arr[$k];

python

b = a.has_key(k)
Back to top

Hash keys

php /* i think */

$a = array_keys($h);

perl

$a = keys %h;

python

a = h.keys
Back to top

Hash values

php /* i think */

$a = array_values($h);

perl

a = values %h;
Back to top

String concatination

php

$s = 'a'.'b';

perl

'a'.'b';

python

'a'+'b';
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','brown')
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?
Back to top

Array to string - join

php

$s = implode($glue,$a);
Back to top

Regular expression match

php

$b = preg_match("/$rx/",$s);

php

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

perl

$b = $s =~ /$rx/;
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;
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 'data.txt', FH;
for $line (<FH>) {
  chomp $line;
}
close FH;
or can for (<FH>) and $line = $_

python

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

fopen(...),fputs(...),fclose(...);
*i think*, incomplete anyway
Back to top

Read contents from an external website

php /* download something that implements cURL for anything more advanced using HTTP */

$s = file_get_contents($url);
Back to top

Call a system command, get output

php

ob_start();
system('yada');
$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

Else if

php

else if
elseif
either is fine

python

elif

perl

elsif
Back to top

Deleting varaiables

php

unset($var);
Back to top

php

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

perl

use Data::Dumper;
print Dumper \$var;
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);
 
Back to top

Mysql query return assoc

php

$result = mysql_query($sql);
while ($row = mysql_assoc($result))
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

Class

php

class MyClass extends MyParent {
  var $my_var = 15;
  function MyClass($arg) { // constructor - __construct for php5 ??
  $this->MyParent($arg); // super
  }
}
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 throgh 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