Syntax
Here is a comparison of programming language syntax which highlights the syntax equivalents of useful language features across several that I use for both research and commercial coding. This is a work in progress consisting of reference and practical examples of converting code when switching between programming languages.
COMMENTS
Coldfusion: <!- - - boo - - ->
PHP: /* boo */
Ruby: =begin boo =end
Python: ‘ ‘ ‘ boo ‘ ‘ ‘
Javascript: /* boo */
JSP/JSTL: /* boo */
Perl: =begin boo =end
HERE DOCUMENT
Coldfusion: N/A
PHP:
<?
$firstname = “jim”;
$lastname = “walker”;
$message = “How do you do?”
echo <<blockotext
I am $firstname $lastname.
$message
blockotext;
?>
Ruby:
firstname = “jim”
lastname = “walker”
message = “How do you do?”
puts <<blockotext
I am #{firstname} #{lastname}.
#{message}
blockotext
Python:
firstname = “jim”
lastname = “walker”
message = “How do you do?”
print(”"”\
I am %(firstname) %(lastname).
%(message)
“”" % locals() )
Javascript: N/A
JSP/JSTL: N/A
Perl:
$firstname = “jim”;
$lastname = “walker”;
$message = “How do you do?”
print <<blockotext
I am $firstname $lastname.
$message
blockotext;
OPERATORS
Coldfusion: EQ or = = or IS
PHP: = = = or = =
Ruby: = =
Python: = = or IS
Javascript: = = = or = =
JSP/JSTL: = =
Perl: = =
Coldfusion: NEQ or != or IS NOT
PHP: != or != =
Ruby: !=
Python:!= or <> or IS NOT
Javascript:!= or != =
JSP/JSTL: !=
Perl: !=
Coldfusion: GT or >
PHP: >
Ruby: >
Python:>
Javascript:>
JSP/JSTL: >
Perl: > or GT
Coldfusion: GTE or >=
PHP: >=
Ruby: >=
Python:>=
Javascript:>=
JSP/JSTL: >=
Perl: >= or GE
Coldfusion: <cfset result = CompareNoCase(a,b)>
PHP: <? $result = strcmp(a,b); ?>
Ruby: result = a <=> b
Python: result = cmp(a,b)
Javascript: var result = (a===b) ? 0 : (a>b) ? 1 : -1
JSP/JSTL:
Perl: $result = $a <=> $b;(numbers)
$result = $a cmp $b; (strings)
Coldfusion: <cfif B GT 0> <cfset vehicle = ‘jeep’> <cfelse> <cfset vehicle = ‘bus’></cfif>
PHP: <? $vehicle = $B ? ‘jeep’ : ‘bus’; ?>
Ruby: vehicle = B ? ‘jeep’ :’bus’
Python: vehicle = ‘jeep’ if B else ‘bus’
Javascript: vehicle = B ? ‘jeep’ :’bus’
JSP/JSTL:
Perl: $vehicle = $B ? ‘jeep’ : ‘bus’;
SIGILS
Coldfusion: # - variable
PHP: $ - variable
Ruby: $ - global variable
@ - object instance variable
@@ - object class variable
# - string interpolation
Python: % - string interpolation
Javascript: N/A
JSP/JSTL: $ - variable
Perl: $ - scalar
@ - array
% - hashmap
& - subroutine call
NAMESPACES
Coldfusion: application, session, client, server, request, query, form, cgi, cookie, url, attributes, caller, variables(local scope), var(function scope), this
PHP: function, global, static, class, private, public, protected, final
Ruby: def, global, class, private, public, protected
Python: def, global, class, module
Javascript: var, window, document, function, object, global
JSP/JSTL:
Perl: sub, global, package
VARIABLE EXISTENCE
Coldfusion: <cfif isdefined(”var”)>
PHP: <? if (isset($var) ) ?>
Ruby: if defined?(var)
Python: try:var
except NameError:
var = 0
Javascript: if (var === undefined)
JSP/JSTL: <c:if test=”${!empty var}”>
Perl: if defined($var)
VARIABLE DUMPING
Coldfusion: <cfdump var=”#application#”>
PHP: <? var_dump($application); ?>
Ruby: require yaml
puts YAML::dump(application)
Python: dump(application)
Javascript: N/A without creating a dump function, but alert(application) is a basic alternative
JSP/JSTL:
Perl: use Data::Dumper;
print Dumper $x;
DYNAMIC VARIABLE NAMING
Coldfusion: <cfset myString = #variables["string_'' & myArray[i]]#>
PHP: <? $myString = ’string_’.$myArray[i];?>
Ruby: mystring = ‘’string_”.concat(myArray[i])
Python: mystring = ‘’string_”. + myArray[i]
Javascript: mystring = [''string_'' + myArray[i]];
JSP/JSTL:
Perl: $mystring = “string_” . $myArray[i];
SHORT CIRCUIT EVALUATION
Coldfusion:
<cfif isDefined("x") AND x EQ 1>
<cfset x = x + 1>
</cfif>
PHP:
Ruby:
x = x || 1
Python:
def __init__(self, contents=[]):
self.contents = contents[:]
Javascript:
JSP/JSTL:
Perl:
$realchoice = $userchoice || $systemchoice || $defaultchoice;
RECURSION
Coldfusion:
<cffunction name="factorial">
<cfargument name="factor" required="yes" type="numeric">
<cfif factor LTE 1>
<cfreturn 1>
<cfelse>
<cfreturn factor * factorial(factor -1)>
</cfif>
</cffunction>
PHP:
Ruby:
def factorial(n)
if n == 0
1
else
n * factorial(n-1)
end
end
Python:
def factorial(n)
if n == 0
1
else
n * factorial(n-1)
end
end
Javascript:
function foo(i)
{
if (i < 0) return;
alert('begin:' + i);
foo(i - 1);
alert('end:' + i);
}
foo(3);
/*
begin:3
begin:2
begin:1
begin:0
end:0
end:1
end:2
end:3
*/
JSP/JSTL:
Perl:
sub fact {
my $n = shift;
return 1 if $n < 2;
return $n * fact( $n - 1 );
}
REFLECTION
Coldfusion:
<cfset stringfunc="createObject(">
<cfset argumenttypearray="arrayNew(1)">
<cfset argumenttypearray[1]="createObject(">
<cfset argumenttypearray[2]="createObject(">
<cfset method="stringFunc.getClass().getMethod(">
<cfset comparestring1="This is a test.">
<cfset comparestring2="This is another test.">
<cfset argumentarray="arrayNew(1)">
<cfset argumentarray[1]="compareString1">
<cfset argumentarray[2]="compareString2">
<cfset result="method.invoke(stringFunc,">
<cfoutput>
Compare String 1: #compareString1#
Compare String 2: #compareString2# result = #result#
</cfoutput>
PHP:
$class = "Foo"; $method = "hello"; $object = new $class(); $object->$method();
Ruby:
Class.const_get(:Foo).new.send(:hello)
Python:
instance = 'foo' method = 'Hello' getattr(globals()[instance], method)()
Javascript:
new this['Foo']()['hello']()
JSP/JSTL:
Perl:
my $class = "Foo"; my $method = "hello"; my $object = $class->new(); $object->$method();
MEMOIZING
Coldfusion:
PHP:
Ruby:
def memoize(name)
meth = method(name)
cache = {}
(class << self; self; end).class_eval do
define_method(name) do |*args|
cache.has_key?(args) ? cache[args] : cache[args] ||= meth.call(*args)
end
end
cache
end
end
# Our fibonacci function
def fib(n)
return n if n < 2
fib(n-1) + fib(n-2)
end
Python:
def memoize ( func ) :
remembered = {}
def memoized ( *args ) :
if args in remembered :
return remembered[ args ]
else :
new = func( *args )
remembered[ args ] = new
return new
return memoized
fib_memo = {}
def fib(n):
if n < 2: return 1
if not fib_memo.has_key(n):
fib_memo[n] = fib(n-1) + fib(n-2)
return fib_memo[n]
Javascript:
function getXHR()
{
var xhr;
if (window.XMLHttpRequest)
{xhr = new XMLHttpRequest();}
else if (window.ActiveXObject)
{xhr = new ActiveXObject('Microsoft.XMLHTTP');}
this.getXHR = function() {return xhr;}
return xhr;
}
JSP/JSTL:
Perl:
my @fib;
sub fib
{
my $n = shift;
return $fib[$n] if defined $fib[$n];
return $fib[$n] = $n if $n < 2;
$fib[$n] = fib($n-1) + fib($n-2);
}
LIST COMPREHENSION
Coldfusion:
PHP:
Ruby:
Python:
print [(x,y) for x in (1,2,3,4) for y in (10,15,3,22) if x*y > 25]
Javascript:
function range(n)
{
for (var i = 0; i < n; i++)
yield i;
}
var doubles = [2 * x for (x in range(100)) if (x * x > 3)];
var evens = [i for each (i in range(0, 21)) if (i % 2 == 0)];
JSP/JSTL:
Perl:
COROUTINE
Coldfusion:
PHP:
Ruby:
def evens
Fiber.new do
value = 0
loop do
Fiber.yield value
value += 2
end
end
end
def consumer(source)
Fiber.new do
10.times do
next_value = source.resume
puts next_value
end
end
end
consumer(evens).resume
Python:
Javascript:
JSP/JSTL:
Perl:
CONTINUATION
Coldfusion:
PHP:
Ruby:
def loop
for i in 1..10
puts i
callcc {|c| return c}
if i == 5
end
end
Python:
def f(a, b):
while 1:
(a, b) = (a-b, a+b)
yield (a,b)
x = f(1,2)
x.next()
(-1, 3)
x.next()
(-4, 2)
x.next()
(-6, -2)
Javascript:
var sleep = function(millis)
{
var future = new Future();
setTimeout(future.fulfill, millis);
yield future.result();
};
var animate = function(element, property, endValue, duration, frameTime)
{
// calculate animation variables
var frameCount = Math.ceil(duration/frameTime);
var startValue = parseInt(element.style[property], 10);
var distance = endValue - startValue;
var jumpSize = Math.ceil(distance/frameCount);
// do the animation
for (var i = 0; i < frameCount - 1; i++)
{
var nextValue = startValue + (jumpSize * i);
element.style[property] = nextValue + "px";
// note the yielding operation
yield sleep(frameTime);
}
element.style[property] = endValue + "px";
};
var waitForClick = function(element)
{
var future = new Future();
element.onclick = future.fulfill;
yield future.result();
};
var run = function()
{
var theButton = document.getElementById("theButton");
while(true)
{
theButton.innerHTML = "go right";
// move the button to the right (note the blocking operations)
yield waitForClick(theButton);
theButton.innerHTML = "–>";
yield animate(theButton, "left", 200, 1000, 20);
theButton.innerHTML = "go left";
// move the button to the left (again note the blocking operations)
yield waitForClick(theButton);
theButton.innerHTML = "<–";
yield animate(theButton, "left", 0, 1000, 20);
}
};
JSP/JSTL:
Perl:
MAP FUNCTION
Coldfusion:
PHP:
<?php array_map(create_function('$x', 'return $x + 1;'), array(1, 2, 3, 4, 5) ); ?>
Ruby:
[1, 2, 3, 4, 5].map { |x| 2*x }
Python:
map(lambda x: 2*x, (1, 2, 3, 4, 5) )
Javascript:
function map(fn, a)
{
for (i = 0; i < a.length; i++)
{
a[i] = fn(a[i]);
}
}
var b=[1,2,3,4,5].map(function(x){return x*2});
JSP/JSTL:
Perl:
@b = map { 2 * $_ } (1,2,3,4,5);
REDUCE FUNCTION
Coldfusion:
PHP:
<? array_reduce(array(1, 2, 3, 4, 5), create_function('$x, $y', 'return $x + $y;') ); ?>
Ruby:
module Inject
def inject(n)
each do |value|
n = yield(n, value)
end
n
end
def sum(initial = 0)
inject(initial) { |n, value| n + value }
end
def product(initial = 1)
inject(initial) { |n, value| n * value }
end
end
class Array
include Inject
end
[ 1, 2, 3, 4, 5 ].sum � 15
[ 1, 2, 3, 4, 5 ].product � 120
Python:
reduce(lambda x,y: x+y, [1,2,3,4]) # returns 10
Javascript:
function reduce(fn, a, init)
{
var s = init;
for (i = 0; i < a.length; i++)
s = fn(s, a[i]);
return s;
}
var b = reduce(function(v, w){v += w; return v;}, [1, 2, 3, 4, 5])
JSP/JSTL:
Perl:
sub reduce(&@)
{
my $sub = shift;
#call the anonymous subroutine with the first two elements in @_.
#put the result back into @_ until @_ has only one element, which is the return value:
while( @_ > 1 )
{
unshift @_, $sub->( shift, shift );
}
return $_[0];
}
my @d = ({’title’,'one’, ‘value’,1}, {’value’, 2}, {’value’, 3}, {’title’,'four’, ‘value’,4});
my $s = reduce { $_[0] + $_[1] } @d;
FILTER FUNCTION
Coldfusion:
PHP:
<? array_filter(array(1, 2, 3, 4, 5), create_function('$x', 'return $x % 2 == 0;') ); ?>
Ruby:
evens = [1,2,3,4,5,8,2].select { |i| i & 2 == 0 }
Python:
evens = filter(lambda x: x % 2 == 0, [1,2,3,4,5,8,2])
Javascript:
function filter(fn,a)
{
var matches = [];
for (i = 0; i < a.length; i++)
{
if (fn(a[i]))
{
matches.push(a[i]);
}
}
return matches;
}
var total = [0, 1, 2, 3].filter(function(x){ return x & 1 == 0; });
JSP/JSTL:
Perl:
@evens = grep { $_ & 1 == 0 } (1,2,3,4,5,8,2);
COMPOSE FUNCTION
Coldfusion:
PHP:
Ruby:
Python:
def compose(f, g):
return f(g(x))
compose(sqr, cube, 2)
#64
Javascript:
function compose(f,g)
{
return function(x) { return f(g(x)) }
}
function square(x)
{ return x*x }
function halve(x)
{return x/2}
assert( compose( halve, square ) (4) == 8 )
JSP/JSTL:
Perl:
ANONYMOUS FUNCTION
Coldfusion:
PHP:
$foo = "myFunkyFunc";
$foo($arg, $arg1);
// Calls myFunkyFunk
$foo = create_function('$x','echo "x is $x";');
$foo(5);
// Output: x is 5
Ruby:
lamb = lambda {|x, y| puts x + y}
Python:
foo = lambda x: x*x
Javascript:
var a =
[
function(y) { return y; } ,
function(y) { return y * y; } ,
function (y) { return y * y * y; }
];
print (a[0](5) ) // returns 5
print (a[1](5) ) // returns 25
print (a[2](5) ) // returns 125
JSP/JSTL:
Perl:
(sub { print "I got called\n" })->();
CLOSURE
Coldfusion:
PHP:
function adder ($left)
{
$fA = create_function(’$x’,'return (’ . $left . ‘ + $x);’);
return $fA;
}
$f = adder(5);
echo $f(10);
Ruby:
def foo (n)
lambda {|i| n += i }
end
Python:
def comp(limit): return lambda x: x < limit a = comp(10) b = comp(20) print a(9), a(10), a(20), a(21) #True False False False print b(9), b(10), a(20), b(21) #True True False False
Javascript:
function makeCounter ()
{
var count = 0;
return function()
{return count++;};
};
var counter1 = makeCounter();
var counter2 = makeCounter();
alert(counter1()); // Prints 0
alert(counter1()); // Prints 1
alert(counter2()); // Prints 0
JSP/JSTL:
Perl:
sub make_counter
{
my $initval = shift || 0;
return sub { return $initval++ };
}
my $ctrA = make_counter(10);
my $ctrB = make_counter(20);
print $ctrA->(), "\n";
print $ctrB->(), "\n";
print $ctrB->(), "\n";
print $ctrA->(), "\n";
CURRYING
Coldfusion:
PHP:
function curry($func, $arity) {
return create_function('', "
\$args = func_get_args();
if(count(\$args) >= $arity)
return call_user_func_array('$func', \$args);
\$args = var_export(\$args, 1);
return create_function('','
\$a = func_get_args();
\$z = ' . \$args . ';
\$a = array_merge(\$z,\$a);
return call_user_func_array(\'$func\', \$a);
');
");
}
function sum($a, $b) {
return $a + $b;
}
$sum = curry('sum', 2);
$plus5 = $sum(5);
echo $plus5(10); // 15
$map = curry('array_map', 2);
$toupper = $map('strtoupper');
$ary = array('haskell', 'curry',);
print_r($toupper($ary)); // HASKELL CURRY
Ruby:
def curry(&l)
lambda { |a| lambda { |b| l[a,b] } }
end
ctrue = curry { |a,b| a }
ctrue[1][0]
#1
Python:
def divide(x,y): return x/y def divisor(d): return lambda x: divide(x,d) half = divisor(2) third = divisor(3) print half(32), third(32) #16 10 print half(40), third(40) #20 13
Javascript:
function add(a, b) {
if (arguments.length < 1) {
return add;
} else if (arguments.length < 2) {
return function(c) { return a + c }
} else {
return a + b;
}
}
JSP/JSTL:
Perl:
sub create_roulette_table
{
my $color;
my $money;
my $numbers;
return sub
{
$color = shift;
return sub
{
$money = shift;
return sub
{
push @$numbers, shift;
return sub
{
# play logic here
};
};
};
};
}
# to use, we might do something like:
my $table = create_roulette_table()->('red')->('500')->(8);
$table->(); # play
$table->(); # play again
# or we might do something like:
my $table_no_money = create_roulette_table()->('red')->('500');
my $table;
$table = $table_no_money->(100);
$table->(); # play
$table->(); # play again -- oops, lost everything
$table = $table_no_money->(50);
$table->(); # play some more
INTERNAL ITERATOR
Coldfusion:
PHP:
Ruby:
def fibs(n)
x = 0
y = 1
n.times do
x, y = y, x + y
yield(x)
end
end
Python:
z = [ 'a', 'b', 'c', 'd' ]
for i, item in enumerate(z):
print i, item
0 a
1 b
2 c
3 d
Javascript:
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
function printElt(element, index, array)
{
print("[" + index + "] is " + element); // assumes print is already defined
}
[2, 5, 9].forEach(printElt);
// Prints:
// [0] is 2
// [1] is 5
// [2] is 9
JSP/JSTL:
Perl:
foreach $key (sort(keys %ENV))
{
print $key, '=', $ENV{$key}, "\n";
}
GENERATOR
Coldfusion:
PHP:
Ruby:
def fib():
x = 0
y = 1
while 1:
x, y = y, x + y
yield x
g = fib()
for i in range(9):
print g.next()
Python:
def fib():
x = 0
y = 1
while 1:
x, y = y, x + y
yield x
g = fib()
for i in range(9):
print g.next()
Javascript:
function fib()
{
var i = 0, j = 1;
while (true)
{
yield i;
var t = i;
i = j;
j += t;
}
}
var g = fib();
for (var i = 0; i < 10; i++)
{
alert(g.next() + "<br>\n");
}
JSP/JSTL:
Perl:
CURRENT SCOPE
Coldfusion:this
PHP:$this
Ruby:self
Python:self
Javascript:this
JSP/JSTL:
Perl:my
OBJECT CREATION AND USAGE
Coldfusion:
<cfcomponent name=''Dogcatcher'' extends=''cfc.sql''>
<cffunction name=''foobar'' access=''public'' returntype=''query''>
<cfargument name=''doodoo'' type=''string'' required=''yes''>
<cfquery name=''smell'' datasource=''doghouse''>
select * from sticks where type= '#doodoo#'
</cfquery>
<cfreturn smell>
</cffunction>
</cfcomponent>
<cfinvoke
component=''Dogcatcher''
method=''foobar''
returnvariable=''surprise''
doodoo=''green''
>
<cfoutput>#surprise#</cfoutput>
PHP:
<? class Dogcatcher extends SQL
{
public function foobar($doodoo)
{;}
}
$myFoo = new Dogcatcher;
$surprise = $myFoo->foobar('green');
echo $surprise .''\n'';
?>
Ruby:
class Dogcatcher
def foobar(doodoo)
print ''Creating a new '', self.name, ''\n''
end
end
myFoo = Dogcatcher.new
surprise = myFoo.foobar('green')
puts surprise
Python:
class Simple:
def __init__(self, str):
print "Inside the Simple constructor"
self.s = str
# Two methods:
def show(self):
print self.s
def showMsg(self, msg):
print msg + ':',
self.show() # Calling another method
if __name__ == "__main__":
# Create an object:
x = Simple("constructor argument")
x.show()
x.showMsg("A message")
#:~
Javascript:
function Dogcatcher()
{
function foobar(doodoo)
{
alert('Puppy want some ' + doodoo)
}
}
var trick = Dogcatcher.foobar("treats");
JSP/JSTL:
Perl:
sub query_db
{
my $self = shift;
my @columns = @{$_[0]};
my @tables = @{$_[1]};
my $where = ${$_[2]};
my $hashRef = $_[3];
my %qryHsh = %{$hashRef} if defined $hashRef;
my $is_distinct = $qryHsh{'is_distinct'};
my $order_by = $qryHsh{'order_by'};
my ($stmt, $sth, $result, $all_columns, $all_tables, $i);
my $warning = "";
my @result_set =();
my $distinct = "";
$self->connect_db();
my $dbh = $self->{"DBHandle"};
if ( defined($is_distinct) && $is_distinct == 1 )
{ $distinct = "DISTINCT" };
$all_columns = join(", ", @columns);
$all_tables = join(", ", @tables);
$stmt = "select $distinct $all_columns from $all_tables ";
if ((defined $where) && ($where ne ""))
{
$stmt .= " where $where";
}
if ((defined $order_by) && ($order_by ne ""))
{
$stmt .= " order by $order_by";
}
$sth = $dbh->prepare($stmt) || throw E_DB
("Error in prepare statement in CDB::SQL->query_db **$stmt**\n");
$result = $sth->execute() || throw E_DB
("Error in execute statement in CDB::SQL->query_db **$stmt** " . DBI->errstr);
while (my @a = $sth->fetchrow_array)
{
push(@result_set, \@a);
}
$self->{"RESULT_SET"} = $sth->fetchall_arrayref();
$sth->finish;
return $self->{"RESULT_SET"};
}
OBJECT INITIALIZERS/CONSTRUCTORS
Coldfusion:
PHP:
class rep
{
var $parameters=array();
function __construct( $select, $update, $eval)
{
$this->parameters['select'] = $select;
$this->parameters['update'] = $update;
$this->parameters['eval'] = $eval;
}
function run()
{
$args = func_get_args();
$selections = call_user_func_array( $this->parameters['select'], args);
$updates = call_user_func_array( $this->parameters['update'], $selections);
return call_user_func_array( $this->parameters['eval'], $updates);
}
}
Ruby:
Python:
Javascript:
var person = {
name: "Gina Vechio",
children: [ "Ruby", "Chickie", "Puppa"]
};
JSP/JSTL:
Perl:
sub new
{
my $class = shift;
my %opts = @_;
my $self =
{
DBHandle => undef, # Actual Database Handle
Databases => [], # List of database opt sets
};
$self->{'CACHE_PATH'} = $opts{'CACHE_PATH'} || $DefaultCDBCache;
$self->{'USER'} = $opts{'USER'} || (getpwuid($>))[0]
|| $ENV{'USER'} || $ENV{'LOGNAME'} || 'unknown';
$self->{'TRANSACTION'} = $opts{'TRANSACTION'} || 0;
$self->{'CONNECTED'} = 0; # We're making a new connection
bless ($self, $class);
$self->_load_cdbrc();
foreach my $default ( @DefaultOpts )
{
my %info;
foreach my $arg ( keys %$default )
{
$info{$arg} ||= $default->{$arg};
}
push( @{ $self->{'Databases'} }, \%info );
}
return $self;
}
CALLBACKS
Coldfusion:
PHP:
<?
function my_callback_function()
{
echo 'hello world!';
}
class MyClass
{
function myCallbackMethod()
{
echo 'Hello World!';
}
}
call_user_func('my_callback_function');
call_user_func_array('MyClass', 'myCallbackMethod');
$obj = new MyClass();
call_user_func_array($obj, 'myMethod');
$cube = create_function('$i', 'return $i * $i * $i;');
$a = array(1, 2, 3, 4, 5);
$b = array_map($cube, $a);
print_r($b);
?>
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:
MIXIN INHERITANCE
Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:
HASHMAP INITIALIZATION
Coldfusion: <cfset h = StructNew()>
<cfset h.a = 1>
PHP: <? $h[a] = 1; ?>
Ruby: h = {}
h[a] = 1
Python:; h = {}
h[a] = 1
Javascript: var h = {};
h[a] = 1;
JSP/JSTL: <jsp:useBean id=”map” class=”java.util.HashMap”/>
<c:set target=”${map}” property=”cat” value=”brown”/>
<c:set target=”${map}” property=”dog” value=”green”/>
<c:set target=”${map}” property=”rat” value=”black”/>
Perl: %h = (”a”, 1);
HASHMAP SEARCH
Coldfusion: <cfif StructKeyExists(h, “a”)>
PHP:<? if (in_array(”a”, $h) ) ?>
Ruby: if (h.has_key?(”a”) )
Python: if (h.has_key(”a”) )
Javascript:
JSP/JSTL:
Perl: if (exists $h{a})
DELETE OF HASHMAP KEY
Coldfusion: <cfset removed = StructDelete(h, “a”)>
PHP: $removed = array_splice($h, array_search(”a”,$h), 1);
Ruby: removed = h.delete(”a”)
Python: removed = del h["a"]
Javascript:
JSP/JSTL:
Perl: $removed = delete $h{a};
VALUE OF HASHMAP KEY
Coldfusion: <cfset myval = h.a>
PHP: <? $myval = $h["a"] ?>
Ruby: myval = h["a"]
Python: myval = h["a"]
Javascript: var myval = h["a"]
JSP/JSTL:
Perl: $myval = $h{a};
ARRAY OF HASHMAP KEYS
Coldfusion: <cfset allkeys = StructKeyArray(h)>
PHP: <? $allkeys = array(array_keys($h) ) ?>
Ruby: allkeys = h.keys
Python: allkeys = h.keys()
Javascript:
JSP/JSTL:
Perl: @allkeys = keys %h;
ARRAY OF HASHMAP VALUES
Coldfusion:
PHP: <? $allvalues = array(array_values($h) ) ?>
Ruby: allvalues = h.values
Python: allvalues = h.values()
Javascript:
JSP/JSTL:
Perl: @allvalues = values %h;
ARRAY INITIALIZATION
Coldfusion: <cfset blog = ArrayNew(1)#>
<cfset temp = ArraySet(blog,1,6,”0”)>
<cfoutput>#blog[3]#</cfoutput>
PHP: <? $blog = array();?>
<? $blog = array_fill(1,6,”0”);?>
<? print($blog[3]);?>
Ruby: blog = Array.new
blog[0,6] = ”0”
Python: from array import array
a = array(0,0,0,0,0,0)
Javascript: a = [];
JSP/JSTL:
Perl: @blog = (0,0,0,0,0,0) ;
$blog[2];
ARRAY LENGTH LOOPING
Coldfusion: <cfloop from=”0” to=”#ArrayLen(blog)#” index=”counter”>
PHP: <? for i=”0”; i<=$blog.count()”; i++ ?>
Ruby: for i in blog.length
Python: for i in len(blog)
Javascript: for (i=0; i <= blog.length; i++)
JSP/JSTL: for(i=0; i <= ${fn:length(blog)})
Perl: foreach $i (@blog)
ARRAY PUSH
Coldfusion: <cfoutput>#ArrayAppend(blog,3,”makaveli”)#</cfoutput>
PHP: <? $blog[] = ‘makaveli’;?>; //No insertAt equivalent
Ruby: blog << ‘makaveli’
Python: blog.append(’makaveli’);
Javascript: blog.push(’makaveli’);
JSP/JSTL:
Perl: push(@blog,’makaveli’);
ARRAY POP
Coldfusion: <cfoutput> #ListFirst(data)#”</cfoutput>
PHP: <? $popee = array_pop($data); ?>
Ruby: popee = data.pop
Python: popee = data.pop()
Javascript: popee = data.pop();
JSP/JSTL:
Perl: $popee = pop(@data);
ARRAY FIND
Coldfusion: <cfif ListFind(”tupac”, ”tupac”)>
PHP: <? if array_key_exists(’tupac’, array(’tupac’)>
Ruby: if tupac.index(”tupac”)
Python: if tupac.index(”tupac”)
Javascript: if ( (”tupac”).toString.indexOf(”tupac”)
JSP/JSTL:
Perl: if (grep /^$rel1$/, @released){print “Result = $rel1\n”;}
ARRAY SEARCHING
Coldfusion: <cfset result = ListContains(”2,4,6,8,10”, ”10”)>
PHP: <? $result = array_search(10, array(2,4,6,8,10) ); ?>
Ruby: result = [2,4,6,8,10].include?(10)
Python: result = array(2,4,6,8,10).count(10)
Javascript: result = (2,4,6,8,10).join().indexOf(10)
JSP/JSTL:
Perl: $result = index(join((2,4,6,8,10),10);
ARRAY REPLACEMENT
Coldfusion: <cfset splice= ListContains(”2,4,6,8,10”, ”10”)>
PHP: <? $splice = array_splice(array(2,4,6,8,10),0,1,”0”); ?>
Ruby: splice = Array[ 2,4,6,8,10]
splice[0,1] = 0
Python: splice= array(2,4,6,8,10).remove(2)
splice= array(2,4,6,8,10).insert(0,1)
Javascript: splice = (2,4,6,8,10).splice(1,2,0,1)
JSP/JSTL:
Perl: @array = (2,4,6,8,10)
$splice = splice(@array,0,1,0)
ARRAY INSERTION
Coldfusion: <cfset insert = ArrayInsertAt(”2,4,6,8,10”, 2, ”10”)>
PHP: <? $insert = array_splice(array(2,4,6,8,10),3,0,”9”); ?>
Ruby: insert= Array[ 2,4,6,8,10]
insert[4,0] = 9
Python: insert = array(2,4,6,8,10).insert(9,-1)
Javascript: insert = (2,4,6,8,10).splice(3,0,9)
JSP/JSTL:
Perl: $insert = splice((2,4,6,8,10),3,0,9)
STRING REPLACEMENT
Coldfusion: <cfset headline = Replace(”Yankees Lose.”,”.”,”!”,”All”)
;PHP: <? $headline = str_replace(”.”, ”!”, ”Yankees Lose.”); ?>
Ruby: headline = ”Yankees Lose.”.sub(/\./, ‘!’)
Python: headline = ”Yankees Lose.”.replace(”.”,”!”)
Javascript: headline = ”Yankees Lose”.replace(/\./, ‘!’);
JSP/JSTL: <c:set headline = ${fn:replace(”Yankees Lose.”, .”, ”!”)}/>
Perl: $shortname = substr( ”Yankees Lose.”,13) = “!”;
STRING FIND
Coldfusion: <cfif Find(”pac”, ”tupac”)>
PHP: <? if (strpos(”tupac”, ”pac”) = = = false) ?>
Ruby: if ”tupac”.include?(”pac”)
Python: if ”tupac”.find(”pac”)
Javascript: if (”tupac”.indexOf(”pac”) )
JSP/JSTL: <c:if test=”${fn:contains(tupac, pac)}”>
Perl: if (index(”tupac”,”pac”) )
STRING INSERTION
Coldfusion: <cfoutput> #Insert(”.”, ”Hello My name is Fred”,5)#</cfoutput>
PHP: <? str_replace(”Hello”, ”Hello.”, ”Hello My name is Fred”); ?>
Ruby: ”Hello My name is Fred”.insert(5,’.')
Python: ”Hello My name is Fred”.replace(”Hello”, ”Hello.”)
Javascript: ”Hello My name is Fred”.replace(/Hello/, ”Hello.”)
JSP/JSTL: <c:set ${fn:replace(”Hello My name is Fred”, ”Hello”, ”Hello.”)}/>
Perl:substr(”Hello My name is Fred”, 6) = “.”;
STRING TRUNCATION
Coldfusion: <cfset shortname = RemoveChars(”Tupac”, 1, 2)> //returns ”pac”
PHP: <? $shortname = substr(”Tupac”, 2) ?>
Ruby: shortname = ”Tupac”[2,3]
Python: shortname = ”Tupac”.lstrip(”Tu”)
Javascript: shortname = ”Tupac”.substring(2,3);
JSP/JSTL: <c:set shortname: ${fn:substring(zip, 6, -1)} />
Perl: $shortname = substr(”Tupac”,2,3);
REGULAR EXPRESSION MATCHING
Coldfusion:
<cfset where = REFind ("[Uu]\.?[Ss]\.?[Aa}\.?", Report )>
PHP:
<?php
/* The \b in the pattern indicates a word boundary, so only the distinct
* word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice."))
{
echo "A match was found.";
}
else
{
echo "A match was not found.";
}
if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice."))
{
echo "A match was found.";
}
else
{
echo "A match was not found.";
}
?>
Ruby:
johnsays = “It's 9:18PM here now.I cannot wait to go out tonight.” time = /\d\d:\d\d/ if johnsays=~time puts “John told you what time it is.He is eager to go out.” else puts “John does not care what time it is.He is too tired to go out.” end
Python:
import re
text = "The Attila the Hun Show"
# match a single character
m = re.match(".", text)
# print the matching string
if m: print repr("."), "=>", repr(m.group(0))
Javascript:
JSP/JSTL:
Perl:
while (defined($paragraph = <>))
{
while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g)
{
$sentences++;
}
}
print "$sentences\n";
REGULAR EXPRESSION REPLACEMENT
Coldfusion:
<cfset newtext = REReplace("I love jellies","jell(y|ies)","cookies")>
PHP:
<? $string = 'The quick brown fox jumped over the lazy dog.'; $patterns[0] = '/quick/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $replacements[2] = 'cat'; $replacements[1] = 'orange'; $replacements[0] = 'slow'; echo preg_replace($patterns, $replacements, $string); ?>
Ruby:
"fred:smith".sub(/(\w+):(\w+)/. '\2, \1') -> smith, fred
Python:
import re
text = "you're no fun anymore..."
# literal replace (string.replace is faster)
print re.sub("fun", "good", text)
Javascript:
JSP/JSTL:
Perl:
# Replace foo with bar.
s {foo} {bar}
DATE FORMATTING
Coldfusion: <cfoutput> #Dateformat(now(), ”mmm dd, yyyy”)#</cfoutput>
PHP: <? echo date(”M d, Y”); ?>
Ruby: date.month date.day date.year
Python: from datetime import date
date.today()
Javascript: var today = new Date();
var Year = takeYear(today);
var Month = leadingZero(today.getMonth()+1);
var DayName = Days[today.getDay()];
var Day = leadingZero(today.getDate());
var Hours = leadingZero(today.getHours());
var Minutes = leadingZero(today.getMinutes());
var Seconds = leadingZero(today.getSeconds());
JSP/JSTL: <%@page import=”java.util.*” %>
Date today = new Date();
Perl: $today = (localtime)[4] . (localtime)[6] . “,” . (localtime)[7];
TYPE CONVERSION
Coldfusion: <cfset nameArray = ListToArray(”2,4,6,8,10”)>
PHP: <? $nameArray = (array) ”2,4,6,8,10”; ?>
Ruby: nameArray = ”2,4,6,8,10”.to_a
Python: nameList = array(2,4,6,8,10).tolist()
Javascript: nameString = (2,4,6,8,10).toString
JSP/JSTL: <c:set ${fn:join(array, ”,”)}/>
Perl: @blues= (2,4,6,8,10);
%is_blue = ();
for (@blues) { $is_blue{$_} = 1 }
URL ENCODING
Coldfusion: <cfset location = urlEncodedFormat(”http://www.do.com?start=!1&end=!10”)>
PHP: <? $location = urlencode(”http://www.do.com?start=!1&end=!10”); ?>
Ruby: require ‘uri’
location = URI.escape(”http://www.do.com?start=!1&end=!10”)
Python: import urllib
location = urllib.urlencode(”http://www.do.com?start=!1&end=!10”)
Javascript: location = encodeURIComponent(”http://www.do.com?start=!1&end=!10”);
JSP/JSTL: <% location = response.encodeURL(”url”); %>
Perl: $location=escapeHTML(”http://www.do.com?start=!1&end=!10”);
CGI PARAMETERS
Coldfusion: <cfset loggedIP = CGI.REMOTE_ADDR>
PHP: <? $loggedIP = getenv(’REMOTE_ADDR’); ?>
Ruby: require ‘cgi’
cgi = CGI.new
loggedIP = cgi.remote_addr
Python: import os
import cgi
from cgi import escape
loggedIP = escape(os.environ['REMOTE_ADDR'])
Javascript: referrer = document.referrer
JSP/JSTL: <c:set target=’${header.remote_address}’ />
Perl: $loggedIP = $ENV{’REMOTE_ADDR’};
GETTING FORM FIELD VALUES
Coldfusion: <cfset username = #form.user#>
PHP: <? $username = $_POST['user']; ?>
Ruby: require ‘cgi’
cgi = CGI.new
username = cgi['user']
Python: import cgi
form = cgi.FieldStorage()
username = form.getfirst(”user”, ””).upper()
Javascript: username = document.forms[0]['user'].value
JSP/JSTL: <c:set username=’${param.user}’ />
Perl: use CGI
$form = new CGI;
$username = $form->user;
EMAILING
Coldfusion: <cfmail to = ”2pac” from = ”makaveli” subject = ”outlaw 4 life”>I’m back</cfmail>
PHP:
<? mail(’2pac’, ‘outlaw 4 life’, ‘I”m back’, ‘From:makaveli’ ); ?>
Ruby:
require net/smtp
body = “Wait till they get a load of me”
server = Net::SMTP.start(’localhost’, 25)
server.send_message body, ‘jack@gotham.com’, ‘bat@manor.com’
server.finish
Python: import smtplib
server = smtplib.SMTP(’localhost’)
server.sendmail(’soothsayer@example.org’, ‘jcaesar@example.org’, ”””Beware the Ides of March.”””)
server.quit()
Javascript: N/A
JSP/JSTL:
Perl:
use Net::SMTP;
$smtp = Net::SMTP->new(”localhost”);
$smtp->mail(”admin\@mysite.com”);
$smtp->to(”user\@freemail.com”);
$smtp->data();
$smtp->datasend(”Hello World!\n\n”);
$smtp->dataend();
$smtp->quit();
GETTING/SETTING COOKIES:
Coldfusion:
<cfcookie name = ''restrictions'' value = ''off'' expires = ''NOW''> <cfoutput>#cookie.restrictions#</cfoutput>
PHP:
<? setcookie(''restrictions'',''off'', time() ); ?>
<? echo $_COOKIE[''restrictions'']; ?>
Ruby:
cookie1 = CGI::Cookie::new(''name'' => ''restrictions'', ''value'' => ''off'', ''expires'' = ''NOW'')
cgi.cookies['restrictions']
Python:
import Cookie C = Cookie.SimpleCookie() C[''restrictions''] = ''none'' print C['restrictions'].value
Javascript:
document.cookie = 'restrictions=off; expires=Thu, 2 Aug 2001 20:47:11 UTC;'
cookieString = document.cookie
cookieArray = cookieSet.split(";")
var i = 0
var len = cookieArray.length
for(i=0;i < len; i++)
{
if(cookieArray[i].indexOf("restrictions") )
{
cookieDetails = cookieArray[i].split("=")
cookieName = cookiePairArray[0]
cookieValue = cookiePairArray[1]
}
}
JSP/JSTL:
<% Cookie cookie1 = new Cookie(''restrictions'',''off''); %>
<% response.addCookie(cookie1); %>
<% Cookie[] cookies = request.getCookies(); %>
Perl:
%cookies = fetch CGI::Cookie;
my $c = new CGI::Cookie(-name => 'foo',-value=> 'bar', -expires => '+3M');
$cookies{"foo"};
CODE ABORTING
Coldfusion: <cfabort>
PHP: <? exit(); >
Ruby: exit
Python: sys.exit()
Javascript: return
JSP/JSTL:
Perl: die
EXCEPTION HANDLING
Coldfusion:
<cftry> <cfset name=''#url.name#> <cfcatch> <p>Login Required</p> <cfoutput>#cfcatch.message#><br>#cfcatch.type#</cfoutput> </cfcatch> </cftry>
PHP:
try
{
echo inverse(5) . ''\n'';
echo inverse(0) . ''\n'';
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), ''\n'';
}
Ruby:
throw :quit_requested if res == ''!'' res end catch :quit_requested do
Python:
try:
x = int(raw_input(''Please enter a number: ''))
break
except ValueError:
print ''Oops! That was no valid number. Try again...''
Javascript:
try
{
http_request = new ActiveXObject(''Msxml2.XMLHTTP'');
}
catch (e)
{
alert(e.name + ": " + e.message);
}
JSP/JSTL:
<c:catch var="error">
<c:set var="price" value="${param.unitPrice * param.quantity}"/>
<p> Price: ${price}</p>
</c:catch>
Perl:
eval
{
# Code that could throw an exception (using 'die')
open(FILE, $file) || die "Could not open file: $!";
while ()
{
process_line($_);
}
close(FILE) || die "Could not close $file: $!";
};
if ($@)
{
# Handle exception here. The exception string is in $@
}
SWITCH STATEMENT
Coldfusion:
<cfswitch expression=''#burger#''> <cfcase value=''Big Mac''><cfset response=''Blarg''></cfcase> <cfcase value=''Sourdough Jack'><cfset response=''Excellent!'></cfcase> <cfdefaultcase><cfset response=''Houseburgers are the best''></cfdefaultcase> </cfswitch>
PHP:
<?
switch ($burger)
{
case ''Big Mac'':$response = ''Blarg'';break;
case ''Sourdough Jack'':
$response = ''Excellent!'';
break;
default:
$response = ''Houseburgers are the best'';
}
?>
Ruby:
case variable
when condition1
instruction1
when condition2
instruction2
else instruction k+1
end
Python:
if value == 'option1': function1() elif value == 'option2': function2() elif value == 'option3': function3() else 0
Javascript:
switch (key)
{
case 5:
quizname = document.createTextNode(''SmoothJazzLoop'');
break;
}
JSP/JSTL:
<c:choose>
<c:when test="${customer.category == ’trial’}" >
...
</c:when>
<c:when test="${customer.category == ’member’}" >
...
</c:when>
<c:when test="${customer.category == ’preferred’}" >
...
</c:when>
<c:otherwise>
...
</c:otherwise>
</c:choose>
Perl:
SWITCH:
{
if (/^abc/) { $abc = 1; <a href="http://perldoc.perl.org/functions/last.html">last</a> SWITCH; }
if (/^def/) { $def = 1; <a href="http://perldoc.perl.org/functions/last.html">last</a> SWITCH; }
if (/^xyz/) { $xyz = 1; <a href="http://perldoc.perl.org/functions/last.html">last</a> SWITCH; }
$nothing = 1;
}
DATABASE TRANSACTIONS
Coldfusion:
<cfquery name = ''timmy'' datasource = ''#prod#''>select * from logs</cfquery>
PHP:
$mysql = $dbh = new PDO('mysql:host=localhost:/tmp/mysql5.sock;dbname=mydb', $myuser, $mypass);
$query = 'SELECT id FROM logs where page = ?';
$result = $dbh->prepare($query);
$result->bindParam(1, $page, PDO::PARAM_INT);
$result->execute();
$rows = $result->fetchall();
Ruby:
require 'dbi'
query = %{ SELECT name, id FROM users WHERE id < 4 }
DBI.connect('DBI:Mysql:test', 'testuser', 'testpwd') do | dbh |
dbh.select_all(query) do | row |
p row
end
end
Python:
import MySQLdb
mysql = MySQLdb.connect(''localhost:/tmp/mysql5.sock '', ''myuser'', ''mysecret'', ''mydb'')
query = mysql.cursor()
try:
query.execute(''select * from yaddayadda'')
except MysqlError, e:
# handle error here
else:
for row in query:
print row
cursor.close()
Javascript: N/A
JSP/JSTL:
<c:set var="bookId" value="${param.Remove}"/>
<jsp:useBean id="bookId" type="java.lang.String" />
<% cart.remove(bookId); %>
<sql:query var="books" dataSource="${applicationScope.mySite}">
select * from PUBLIC.books where id = ?
<sql:param value="${bookId}" />
</sql:query>
Perl:
use 'dbi' $dbh = &dbConnect( $LocalDB::dataSource, $LocalDB::user, $LocalDB::pass); $sql = "SELECT DISTINCT market_segment_id, market_segment"; $sql .= " FROM market_segments"; my $mktSegRef = &dbQuery($dbh, $sql);
TEMPLATE INCLUDE
Coldfusion: <cfinclude template=”test.cfm”>
PHP: <? include(’test.php’) ?>
Ruby: test = file.open(”test.rb”)
Python: execfile(test.py)
OR
file = open(test.py,’r')
exec file
file.close()
Javascript: var script = document.createElement(”script”); script.src = ’test.js’; script.type = ’text/javascript’;
JSP/JSTL: <% jsp:include file=”test.JSP” %>
Perl: use CGI
FILE ACCESS
Coldfusion: <cffile action=”read” file=”readme.txt” variable=”content”>
PHP: <? $content = file_get_contents(”readme.txt”)
Ruby: file = File.open(”readme.txt”)
do |file|
while content = file.gets
Python: file = open(”readme.txt”)
content = read(file)
Javascript: xmlhttp.open(’GET’, “readme.txt”)
content = xmlhttp.responseText;
JSP/JSTL: <c:import url=”readme.txt”/>
Perl: open(INF, “readme.txt”);
@content = <INF>;
HTML HEAD TAG INSERTION
Coldfusion: <cfhtmlhead text = ”<title>This is protected by the Red, Black, and Green</title>”>
PHP:
Ruby:
Python:
Javascript: document.getElementsByTagName(”title”)[0].nodeValue=” This is protected by the Red, the Black, and the Green”;
JSP/JSTL:
Perl:
SHELL COMMAND EXECUTION
Coldfusion: <cfexecute name=”ipconfig.exe” arguments=”/all” />
PHP: exec (ipconfig /all)
Ruby: `ipconfig /all` (backtick method; alternate commands include exec, system, io#popen, open3#popen3)
Python: exec (ipconfig /all)
Javascript: N/A
JSP/JSTL:
Perl: exec (ipconfig /all)
REFERENCES
Language Comparison:
Language Philosophy
Language Transitions
Syntax Comparison
Feature Comparison
Glossary of Languages
Evolutionary Languages
Scripting Language Overview
Language Categories
Language Power
Language Speed
Canonical Syntax Example
Coldfusion:
CFML Reference
Python:
Official Python Tutorial
Python Builtin Functions
Python Command Index
Python Regexp Tutorial
Python Reserved Method Names
Python Primer
Python Anti-FAQ
Python MySQL Tutorial
Python Programming Guide
Introduction to Python
Python Cookbook
Python Database APIs
Python Resources
Python Wiki
Ruby:
Ruby and Rails API Guide
Ruby Tutorials
Official Ruby Documentation
Ruby Builtin Functions
Ruby Users Guide
Ruby Pick Axe Book
Poignant Guide to Ruby
Object Oriented Ruby Guide
Learn to Program using Ruby
PHP:
PHP Language Reference
PHP Function Reference
PHP PDO Reference
PHP Reserved Variables
PHP Regexp Reference
PHP Function Index
PHP Programming Guide
PHP Tutorials
PHP Database Abstraction Class Comparison
Javascript:
JavaScript Language Reference
JScript Language Reference
Javascript Guide
XMLHTTP Reference
Javascript Programming Guide
Javascript Regex and Unicode Tests
AJAX Tutorial
Actionscript 3:
Actionscript 3.0 Programming Guide
Actionscript 3.0 Reference
Actionscript 2:
Actionscript 2.0 Reference
Actionscript 1:
Actionscript Dictionary
JSP/JSTL:
JSP Blog
JSP 2.0 XML Cheat Sheet
JSTL Tutorial
JSTL 1.1 Documentation
JSP 2.0 Syntax Reference
Perl:
Official Perl Documentation
Perl Operators and Regexp
CGI Perl Module Guide
Modular Perl Guide
Object Oriented Perl Guide
Unicode Hex and Character Entities:
HTML and Unicode Punctation and Symbol Codes
Greek Alphabet and Symbol Entities
Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.