Syntax

Here is a comparison of programming language syntax which highlights the syntax equivalents of useful commands across several languages that I use for both personal and professional 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 */%>
OR
<%– boo –%>

Perl: =begin boo =end

VARIABLE OUTPUT

Coldfusion: <cfoutput>#myvar#</cfoutput>

PHP: <?= $myvar ?>

Ruby:

Python:

JavaScript:

JSP/JSTL: <%= myvar %>

Perl:

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;

STRING FORMATTING

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

EQUALITY OPERATORS

Coldfusion: EQ or = = or IS

PHP: = = = or = =

Ruby: = =

Python: = = or IS

Javascript: = = = or = =

JSP/JSTL: = =

Perl: = =

INEQUALITY OPERATORS

Coldfusion: NEQ or != or IS NOT

PHP: != or != =

Ruby: !=

Python:!= or <> or IS NOT

Javascript:!= or != =

JSP/JSTL: != or !fn

Perl: !=

GREATER THAN OPERATORS

Coldfusion: GT or >

PHP: >

Ruby: >

Python:>

Javascript:>

JSP/JSTL: >

Perl: > or GT

GREATER THAN OR EQUAL TO OPERATORS

Coldfusion: GTE or >=

PHP: >=

Ruby: >=

Python:>=

Javascript:>=

JSP/JSTL: >=

Perl: >= or GE

STRING COMPARISON OPERATORS

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)

TERNARY OPERATORS

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

&$ – variable reference call

$$ – dynamic variable variables reference

Ruby:
$ – global variable

@ – object instance variable

@@ – object class variable

# – string interpolation

*xxx – explicit function argument which is a sequence of all unspecified arguments

$_ – implicit global variable which stores the result of the last function or regexp called. It is passed as the default argument to any function if a required parameter is not explicitly passed

<< – assignment

Python:
% – string interpolation

__xxx__ – implicitly called reserved function name

__xxx – object class variable(prepends class name for pseudo namespacing, a.k.a. name mangling)

_xxx – internal object(prevents imports from overwriting this object)

*xxx – explicit function argument which is a sequence of all unspecified arguments

**xxx – explicit function argument which is a hash of all unspecified arguments

Javascript: N/A

JSP/JSTL: $ – variable

Perl:
$ – scalar

@xxx – array

%xxx – hashmap

&xxx – subroutine call

&$xxx – subroutine reference call

\& – pass subroutine argument by reference

$_ – implicit global variable which stores the result of the last function or regexp called. It is passed as the default argument to any function if a required parameter is not explicitly passed

@_ – implicit array variable containing the list of arguments passed to a function

$@ – implicit string variable which stores the result of string evaluation errors encountered during compilation

\@xxx – pass array argument by reference

FALSY VALUES

Coldfusion:

PHP: false, null, “”, “0″, 0

Ruby: false, nil

Python: False, None, “”, (), [], {}, 0

Javascript: false, null, undefined, “”, NaN, 0

JSP/JSTL:

Perl: undef, “”, (), 0

NAMESPACES

Coldfusion: application, session, client, server, request, query, form, cgi, cookie, url, attributes, caller, components, variables(local scope), var(function scope)

PHP: function, global, static, class, private, public, protected, final

Ruby: def, global, class, module, private, public, protected

Python: def, locals, vars, globals, class, module

Javascript: window, document, function, object, global

JSP/JSTL:

Perl: sub, global, package

VARIABLE ASSIGNMENT

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:
XSLT:

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}”> … </c:if>

Perl: if defined($var)

VARIABLE DUMPING

Coldfusion:
<cfdump var=”#application#”>

PHP:
<?
var_dump($application);
?>
(use phpinfo() to dump everything or dbug to emulate cfdump)

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;

FLUSHING OUTPUT

Coldfusion:
<cfflush>

PHP:
<?
ob_flush();
flush();
?>

Ruby:
$stdout.write response.body
$stdout.flush
Python:
cgiprint() or sys.stdout.flush
Javascript: N/A
JSP/JSTL:
Perl: $|=1;

OUTPUT BUFFER CACHING

Coldfusion:
<cfsavecontent variable=”input”>
<cfinclude template=”test.html”>
<cfsavecontent>

PHP:
<?
ob_start();
include(‘test.html’);
$input=ob_get_clean();
?>

Ruby:
Python:
Javascript: N/A
JSP/JSTL:
Perl:

EVALUATING STRING VARIABLE NAMES

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];

CONSTANTS

Coldfusion:

<cfparam name="EmpireStateBuilding" type="regex" pattern="350 5th Avenue, NYC, NY">
#strings
<cfparam name="calendar" type="range" min="365" max="365">
#numbers

PHP:
<? define(“EMPIRESTATEBUILDING”, “350 5th Avenue, NYC, NY”); ?>

Ruby:
EmpireStateBuilding = “350 5th Avenue, NYC, NY”

Python:n/a

Javascript:n/a

JSP/JSTL:

Perl:
use constant EMPIRESTATEBUILDING => “350 5th Avenue, NYC, NY”;

ENUMERATION

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:
XSLT:

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;

IF STATEMENT

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:
XSLT:

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;
  }

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:

<?
function fibonacci ($n)
  {
  if ($n == 1 || $n == 2)
    {
    return 1;
    }
  else
    {
    return fibonacci( $n - 1)+fibonacci( $n - 2 );
    }
  }
?>

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();

MEMOIZATION

Coldfusion:

<cffunction name = "FibCalc">
  <cfargument name = "first_num" type="numeric" required="yes">
  <cfargument name = "second_num" type="numeric" required="yes">
  <cfargument name = "top" type="numeric" required="yes">
  <cfset sequence = arrayNew(1)>
  <cfset total = first_num + second_num>
  <cfset sequence[1] = first_num>
  <cfset sequence[2] = second_num>
  <cfloop condition = "total LTE top">
    <cfset sequence = ArrayAppend(sequence, total)>
    <cfset first_num = second_num>
    <cfset second_num = total>
    <cfset total= (first_num + second_num)>
  </cfloop>
  <cfreturn ArrayToList(sequence, ',')>
</cffunction>

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 = window.XMLHttpRequest ? new XMLHttpRequest() : 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:

l = [1, 2, 3]
l.map{ |i| i * 2 }

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:

@myList = map {$_ * 2} (1..5);

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:

class Baz:
  def __init__(self,foo1,foo2):
    self.one = foo1
    self.two = foo2
  def search(self,info,yes,no):
    return self.one.search(
      info,yes,
      lambda self=self,info=info,yes=yes,no=no: \
      self.two.search(info,yes,no))

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;
    #pass the first two arguments into the subroutine
    #put the result back into until the argument list until it has only one element, 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:

# Builds a function which calls 'f' with
# the return value of 'g'.
def compose f, g
  lambda {|*args| f.call(g.call(*args)) }
end

mult2 = lambda {|n| n*2 }
add1  = lambda {|n| n+1 }
mult2_add1 = compose(add1, mult2)
mult2_add1.call(3) # 7

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:

sub compose
    {
    my ($f, $g) = @_;
    return sub { $f->($g->(@_)); }
    }

COMPLEMENT FUNCTION

Coldfusion:

PHP:

Ruby:

# Builds a function that returns true
# when 'f' returns false, and vice versa.
def complement f
  lambda {|*args| not f.call(*args) }
end

is_even = lambda {|n| n % 2 == 0 }
is_odd  = complement(is_even)
is_odd.call(1) # true
is_odd.call(2) # false

Python:

def complement(f):
    return not f(x)

Javascript:

function complement(f)
   {
   return function(x) { return ! f(x) }
   }

JSP/JSTL:

Perl:

sub complement
  {
  my $f = @_;
  return sub {! $f->(@_); }
  }

CONJOIN FUNCTION

Coldfusion:

PHP:

Ruby:

# Builds a function which returns true
# if every function in the list
# returns true.
def conjoin *predicates
  base = lambda {|*args| true }
  predicates.inject(base) do |built, pred|
    lambda do |*args|
      built.call(*args) && pred.call(*args)
    end
  end
end

is_number = lambda {|n| n.kind_of?(Numeric) }
is_even_number = conjoin(is_number, is_even)

is_even_number.call("a") # false
is_even_number.call(1)   # false
is_even_number.call(2)   # true

Python:

class conjoin(Functor):
    """
    Takes the functions *funcs*, and when called will return 1 if all of
    *funcs* return nonzero when applied to the arguments the conjoin was called with.
    This is basically equivalent to logical and-ing all the functions in *funcs*.
    Note that if a function returns a false (not nonzero) result, the remaining
    functions are not evaluated.
    Example:

    #Function to decide if a number is greater than 5 and less than 10...
    gt5 = lambda x:x > 5
    lt10 = lambda x:x < 10

    between_5_and_10 = conjoin(gt5, lt10)
    """
    def __init__(self, *funcs):
        Functor.__init__(self, funcs[0])
        if not all(funcs, callable):
            raise TypeError, "All arguments must be callable."
        self._funcs = funcs
    def __call__(self, *args, **kwargs):
        for func in self._funcs:
            if not apply(func, args, kwargs):
                return 0
        return 1

Javascript:


JSP/JSTL:

Perl:

sub conjoin
    {
    my ($f, $g) = @_;
    return sub { $f->(@_) && $g->(@_) }
    }

DISJOIN FUNCTION

Coldfusion:

PHP:

Ruby:

# Builds a function which returns true
# if any function in list
# returns true.
def disjoin *predicates
  base = lambda {|*args| false }
  predicates.inject(base) do |built, pred|
    lambda do |*args|
      built.call(*args) || pred.call(*args)
    end
  end
end

is_string  = lambda {|n| n.kind_of?(String) }
is_string_or_number =
  disjoin(is_string, is_number)

is_string_or_number.call("a") # true
is_string_or_number.call(1)   # true
is_string_or_number.call(:a)  # false

Python:

class disjoin(Functor):
    """
    Takes the functions *funcs*, and when called will return 1 if any of
    *funcs* returns nonzero when applied to the arguments the disjoin was called with.
    This is basically equivalent to logical or-ing calls to all the functions in *funcs*.
    Note that if one function returns nonzero, the remaining functions are not
    evaluated. Example:

    #We need to find whether something is a sequence, other than a string.
    isTuple = lambda x:type(x) == type(())
    isList = lambda x:type(x) == type([])
    isUserSeq = lambda x:hasattr(x, '__getslice__')

    isSequence = disjoin(isTuple, isList, isUserSeq)
    """
    def __init__(self, *funcs):
        Functor.__init__(self, funcs[0])
        if not all(funcs, callable):
            raise TypeError("All arguments must be callable.")
        self._funcs = funcs

    def __call__(self, *args, **kwargs):
        for func in self._funcs:
            if apply(func, args, kwargs):
                return 1
        return 0

Javascript:


JSP/JSTL:

Perl:

sub disjoin
    {
    my ($f, $g) = @_;
    return sub { $f->(@_) || $g->(@_) }
    }

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
#################################################
# currying and partial application in python    #
# based on code from Simon Willison's geocoders #
#################################################

# curries fn, a function of exactly 2 parameters
def partial2(fn):
    def inner1(arg2):
        def inner2(arg1):
            return fn(arg1, arg2)
        return inner2
    return inner1

# a simple function of 2 parameters
def hello(firstname, lastname):
    print "hello %s %s" % (firstname, lastname)

hello = partial2(hello)

# perform partial application of hello, binding only the first argument.
# this prints nothing and returns a curried function of 1 parameter
hello_with_firstname = hello('Mickey')

# bind the final argument, which completes the function application
# and finally prints "hello Mickey Mouse"
hello_with_firstname('Mouse')

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:

<?
function fib_iter($num, $show_series="no")
  {
  $retval = "";
  if ($num == 1 )
    {
    return 1;
    }
  $num1 = 1;
  $num2 = 0;
  $retval = "1";

  for ($i = 1; $i &lt; $num; $i++)
    {
    $fib = $num2 + $num1;
    $num2 = $num1;
    $num1 = $fib;
    if ($show_series == 'yes')
      {
      $retval .= ", ".$fib;
      }
    }

  if ($show_series == 'yes')
    {
    return $retval;
    }
  else
    {
    return $fib;
    }
  }
?>

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)
    {
    alert("[" + index + "] is " + element);
    }

[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:

CONTEXT OBJECT

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) &amp;&amp; ($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 COMPOSITION

Coldfusion:
PHP:
Ruby:
Python:

# Speaking pets in Python, but without base classes:
class Cat:
    def speak(self):
        print "meow!"

class Dog:
    def speak(self):
        print "woof!"

class Bob:
    def bow(self):
        print "thank you, thank you!"
    def speak(self):
        print "hello, welcome to the neighborhood!"
    def drive(self):
        print "beep, beep!"

def command(pet):
    pet.speak()

pets = [ Cat(), Dog(), Bob() ]

for pet in pets:
    command(pet)

Javascript:
JSP/JSTL:
Perl:

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:

class Rect:
    def __init__(self, width, height):
        self.width = width
        self.height = height

myRect = Rect(5, 7)

Javascript:

var person = Profile
                  {
                  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 odd($var)
{
   return($var & 1);
}

function even($var)
{
   return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));

Odd Array:
[a] => 1
[c] => 3
[e] => 5
Even Array:
[0] => 6
[2] => 8
[4] => 10
[6] => 12

Ruby:

[1,2,3,4,5].map{ |i| i**2 }

Python:

def square(n):
    return n * n

numbers = [1, 3, 5, 7]

squares1 = [square(n) for n in numbers]     # list comprehension

Javascript:

function do_callback(num)
  {
  document.write(num + "<br>\n");
  }

function fib()
  {
  var i = 0, j = 1, n = 0;
  while (n < 10)
    {
    do_callback(i);
    var t = i;
    i = j;
    j += t;
    n++;
    }
  }

JSP/JSTL:

Perl:

package Calc;
use strict; use warnings;

sub calculate
    {
    my $class     = shift;   # discarded
    my $data      = shift;
    my $rate_calc = shift;   # a code ref
    my $tax_calc  = shift;   # also a code ref

    my $rate      = &$rate_calc($data);
    my $taxes     = &$tax_calc($data, $rate);
    my $answer    = $rate + $taxes;
    }

#!/usr/bin/perl
use strict; use warnings;

use Calc;

my $rental =
    {
    days_used    => 5,
    day_rate     => 19.95,
    tax_rate     => .13,
    };

my $amount_owed = Calc->calculate($rental, \&rate_calc, \&taxes);
print "You owe $amount_owed\n";

sub rate_calc
    {
    my $data = shift;
    return $data->{days_used} * $data->{day_rate};
    }

sub taxes
    {
    my $data     = shift;  # discarded
    my $subtotal = shift;

    return $data->{tax_rate} * $subtotal;
    }

MIXIN INHERITANCE

Coldfusion:
PHP:

class Person
    {
    var $job = "person";
    function show_job()
        {
        echo "Hi, I work as a {$this->job}.";
        }
    }

class Bartender
    {
    var $job = "bartender";
    function show_job()
        {
        echo "BARTENDER: ";
        Person::show_job();
        }
    } 

$b = new Bartender; $b->show_job();

Ruby:

module Adding
    def add(value_one, value_two)
        return value_one + value_two
    end
end

module Subtract
    def subtract(value_one, value_two)
        return value_one - value_two
    end
end

class Mathmagician
    include Adding
    include Subtract
end

mathmagician = Mathmagician.new()

puts "The difference between my looks and your looks is: " + mathmagician.subtract(10,2).to_s
puts "Our combined looks are " + mathmagician.add(10,2).to_s

Python:

class abc(object):
    def jkl(self):
        print "hello, world"

def ghi(self, string):
    print string

abc.ghi = ghi

a = abc()
a.jkl()
a.ghi("this is a test")

#hello, world
#this is a test

Javascript:

var alpha =
    {
    foo: function()
        {
        return "alpha's foo";
        }
    };

var beta =
    {
    bar: function()
        {
        return "beta's bar";
        }
    };

var myObj =
    {
    include: function(mixin)
        {
        this.mixins = this.mixins || [];
        this.mixins.push(mixin);
        },
    send: function(method)
        {
        if (this[method])
            {
            return this[method]();
            }
        for (var i=0, len=this.mixins.length; i<len; i++)
            {
            var mixin = this.mixins[i];
            if (mixin[method])
                {
                return mixin[method]();
                }
            }
        },
    foo: function()
        {
        return "myObj's foo";
        }
    };

myObj.include(beta);
myObj.include(alpha);
myObj.send('foo'); // --> "myObj's foo"
myObj.send('bar'); // --> "beta's bar"

JSP/JSTL:
Perl:

package Calc;

sub calculate
    {
    my $self = shift;
    my $rate = $self->calculate_rate();
    my $tax  = $self->calculate_tax($rate);
    return $rate + $tax;
    }

1;

package CalcDaily;
package Calc;
use strict; use warnings;

sub new
    {
    my $class = shift;
    my $self  =
        {
        days_used    => shift,
        day_rate     => shift,
        tax_rate     => shift,
        };
    return bless $self, $class;
    }

sub calculate_rate
    {
    my $data = shift;
    return $data->{days_used} * $data->{day_rate};
    }

sub calculate_tax
    {
    my $data     = shift;  # discarded
    my $subtotal = shift;
    return $data->{tax_rate} * $subtotal;
    }

1;

METACLASSES

Coldfusion:
PHP:

<?php
class Even {
	const CLASS_NAME = 'Even';
	static function identify()
		{echo 'This is the Even class.';}
}

class Odd {
	const CLASS_NAME = 'Odd';
	static function identify()
		{echo 'This is the Odd class.';}
}

// Choose one of the two classes to call the identify function
$class = (time() % 2 == 0) ? 'Even' : 'Odd';

call_user_func(array($class,'identify'));

echo constant($class . '::CLASS_NAME');

Ruby:

class Foo
  def hello
    print "hello"
  end
end

foo = Foo.new
foo.hello

#add class-level functionality to just the foo instance of the Foo class
class << foo
#add an attribut name/value pair to this instance
attr :name, TRUE
#define a method which calls this attribute
  def hello
    "hello. I'm " +  @name + "\n"
  end
end

foo.name = "Tom"
foo.hello        # -> "hello. I'm Tom\n"

#We've customized foo without changing the characteristics of Foo
class Barker
  #call a metaclass method

  def self.sayer(meth_name)
    #add a method to the metaclass
    define_method meth_name do
      puts "#{meth_name}!!"
    end
  end
  #add attributes to the metaclass method
  sayer :hey
  sayer :stop!
end
b = Barker.new
b.hey
b.stop
#self.sayer wasn't a method in the Class itself, but in it's metaclass

Python:

class MetaClass(type):
    def __new__(meta, classname, bases, classDict):
        print 'Class Name:', classname
        print 'Bases:', bases
        print 'Class Attributes', classDict
        return type.__new__(meta, classname, bases, classDict)

class Test(object):
    #add metaclass functionality to the Test class

    __metaclass__ = MetaClass

    def __init__(self):
        pass

    def method(self):
        pass

classAttribute = 'Something'

Javascript:

function act_as_compound(target)
    {
    target.appendNamedChild = function(name, tag, props)
       {
       var child = document.createElement(tag);
       this.appendChild(child);
       this[name] = child;
       if (props != null)
           {
           Object.extend(child, props);
           }
       return child;
       }
    target.appendSpan = function(name, props)
       {
       return this.appendNamedChild(name, 'SPAN', props);
       }
    target.appendDiv = function(name, props)
       {
       return this.appendNamedChild(name, 'DIV', props);
       }
    target.appendButton = function(name, props)
       {
       var btn = this.appendNamedChild(name, 'button', props);
       return btn;
       }
    return target;
    }

function Pager(pager, controller)
    {
    if (!pager)
        {
        pager = document.createElement('div');
        }
    // Metaprogramming constructs -- add in the methods to support the
    // compound element
    act_as_compound(pager);
    controlled_by(pager, controller);
    var pageFunction = function()
        {
        controller.goToPage(this.pageNumber);
        }
    // Use the methods on act_as_compound to add child elements to the parent div
    pager.appendButton('firstButton', {innerHTML: '|&lt;', pageNumber: 1});
    pager.appendButton('previousButton', {innerHTML: '&lt;&lt;'});
    pager.appendSpan('pageSpan');
    pager.appendButton('nextButton', {innerHTML: '&gt;&gt;'});
    pager.appendButton('lastButton', {innerHTML: '&gt;|'});
    pager.buttons = [pager.firstButton, pager.previousButton, pager.nextButton, pager.lastButton];
    pager.buttons.each( function(button)
        {
        button.controller = controller;
        button.onclick = function()
            {
            this.controller.goToPage(this.pageNumber);
            }
        });
    return pager;
    }

JSP/JSTL:
Perl:

DECORATORS

Coldfusion:
PHP:
Ruby:
Python:

def elementwise(fn):
    def newfn(arg):
        if hasattr(arg,'__getitem__'):  # is a Sequence
            return type(arg)(map(fn, arg))
        else:
            return fn(arg)
    return newfn

@elementwise
def compute(x):
    return x**3 - 1

print compute(5)        # prints: 124
print compute([1,2,3])  # prints: [0, 7, 26]
print compute((1,2,3))  # prints: (0, 7, 26)

Javascript:
JSP/JSTL:
Perl:

MONADS

Coldfusion:
PHP:
Ruby:
Python:

class Maybe:
    def __init__(self, value=None):
        self.value = value

    def __repr__(self):
        return "Maybe(%s)" % self.value

    def pass_to(self, callback):
        # "pass" is a keyword, so I've used the name "pass_to".
        if self.value is None:
            return Maybe(None)
        return callback(self.value)

    def add(left_monad, right_monad):
        monad_class = left_monad.__class__
        # This strange indentation is perhaps more readable.
        return left_monad.pass_to(lambda left_value:
            (
            right_monad.pass_to(lambda right_value:
                (
                monad_class(left_value + right_value)
                )
            )
        )
    )

n1 = Maybe(5)
n2 = Maybe(6)
n3 = Maybe(None)

print n1, "+", n2, "=", add(n1, n2)
# => Maybe(5) + Maybe(6) = Maybe(11)

print n2, "+", n3, "=", add(n2, n3)
# => Maybe(6) + Maybe(None) = Maybe(None)

Javascript:

function MonadClass(value)
  {
  this.value = value || undefined;
  }

MonadClass.prototype.pass = function(value, cb, scope)
  {
  if typeof value["value"] == undefined)
    {
    return new this.constructor();
    }
  if(scope)
    {
    return cb.call(scope, value);
    }
  return cb(value);
  }

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 (array_key_exists("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:
var obj = { val: 'Some string' }
delete obj.val
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:
var allkeys=[];
for(var i in h)
{
allkeys.push(i);
}

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:
var allvalues=[];
for(var i in h)
{
allvalues.push(i.value);
}
JSP/JSTL:

Perl: @allvalues = values %h;

HASHMAP TRAVERSAL

Coldfusion:

PHP: <? foreach ($h as $key => $value) ?>

Ruby:

Python:

Javascript:

JSP/JSTL:

Perl:

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: <? foreach ($blog as $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'); #unshift adds a new value at the first index

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); #shift removes the value at the first index

ARRAY BOOLEAN SEARCH

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 INDEX 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= ReplaceList(''2,4,6,8,10'', "2,4", "0")>

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)

NUMERIC ARRAY SORT

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

STRING TO ARRAY CONVERSION

Coldfusion: <cfset nameArray = ListToArray(''2,4,6,8,10'')>

PHP: <? $nameArray = explode(",", ''2,4,6,8,10''); ?>

Ruby: nameArray = ''2,4,6,8,10''.to_a

Python:
sent = 'colorless;green;ideas;sleep;furiously'
nameArray = sent.split(';')
#['colorless', 'green', 'ideas', 'sleep', 'furiously']
Javascript:

JSP/JSTL:

Perl:

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)}''> ... </c:if>

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);

STRING SLICING

Coldfusion:
PHP:
Ruby:
Python:
msg[6:]
msg[:3]
Javascript:
JSP/JSTL:
Perl:

CAPITALIZING STRINGS

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

LOWERCASING STRINGS

Coldfusion:
PHP:
Ruby:
Python:
sent = ['The', 'dog', 'gave', 'John', 'the', 'newspaper']
>>> [word.lower() for word in sent]
['the', 'dog', 'gave', 'john', 'the', 'newspaper']
Javascript:
JSP/JSTL:
Perl:

ARRAY TO STRING CONVERSION

Coldfusion: < >

PHP: <? $nameString = implode(",", array(2,4,6,8,10) ); ?>

Ruby:

Python:

Javascript:

JSP/JSTL:

Perl:

RANDOM NUMBER GENERATION

Coldfusion:

PHP:
$secret_num = rand(1, 10)

Ruby:
secret_num = rand(10)

Python:
secret_num = random.randint(1, 10)

Javascript:
var secret_num = Math.floor(Math.random() * 10);

JSP/JSTL:
Perl:
$secret_num = int(rand(10) );

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:

var browser = navigator.appVersion;
var Safari = /Safari/;

if (Safari.test(browser) )
  {
  if (document.getElementById("newscontent") )
    {
    document.getElementById("newscontent").setAttribute("overflow", "scroll");
    }
  }

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:

function setupParameters()
  {
  var parameters = {};
  if(window.location.search)
    {
    var paramArray = window.location.search.substr(1).split('&');
    var length = paramArray.length;
    for (var index = 0; index <length; index++ )
      {
      var param = paramArray[index].split('=');
      var name = param[0];
      var value =
         typeof param[1] == "string"
         ? decodeURIComponent(param[1].replace(/\+/g, ' '))
         : null;
       parameters[name] = value;
       }
    }
  window.location.parameters = parameters;
  }

JSP/JSTL:

Perl:

# Replace foo with bar.
s {foo} {bar}

CHARACTER TYPE CHECKING(Posix or Regex)

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

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];

LEAP YEAR CHECKING

Coldfusion:
<cfoutput> #IsLeapYear(now() )# </cfoutput>

PHP:

<?
/* Check current year */
$is_leap = date('L', time() );

function is_leapyear($year)
  {
  $is_leap = date('L', strtotime($year) );
  return $is_leap;
  }
?>

Ruby:

Python:

import calendar;

def is_leapyear(year)
  return calendar.isleap(year)

JavaScript:

/*
Check whether the given year is divisible by 4 and is either not divisible by 100 or divisible by 400
This is the definition of a leap year and as a result February has 29 days
*/
function is_leapyear(year)
  {
  return(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) );
  }

JSP/JSTL:

Perl

use Date::Calc qw(leap_year);

$year = 2000;
print "$year is a leap year\n" if ( leap_year($year) );

REQUEST TIMEOUT

Coldfusion:

PHP:
<? set_time_limit(15); ?>
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

CALENDAR ACCESS

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

TASK SCHEDULING

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

DATA TYPE CHECKING

Coldfusion:
PHP:
Ruby:
Python:
oddments = ['cat', 'cat'.index('a'), 'cat'.split()]
for e in oddments:
type(e)
#'str'
#'int'
#'list'
Javascript:
JSP/JSTL:
Perl:

TYPE CONVERSION

Coldfusion: <cfset nameArray = ListToArray(''2,4,6,8,10'')>

PHP: <? $nameArray = settype(''2,4,6,8,10'', "array"); ?>

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'');

URL Redirection

Coldfusion: <cflocation url="http://www.do.com">

PHP: <? header('Location:http://www.do.com'); ?>

Ruby:
require 'net/https'
request = Net::HTTP::Post.new(url.path)
request['Location'] = "http://www.do.com"

Python:
import urllib2
Request.add_header("Location", "http://www.do.com")

Javascript: this.location.href='http://www.do.com';

JSP/JSTL: <% response.setHeader("Location", "http://www/do.com"); %>

Perl: print "Location: http://www.do.com\n\n";

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='${request.getRemoteAddr()}' />

Perl: $loggedIP = $ENV{'REMOTE_ADDR'};

CGI DEBUGGING

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

STACK TRACING

Coldfusion:

<cffunction name="StackTrace" access="public" returntype="void" output="false">
  <cfset var Trace = StructNew() />

  <cftry>
    <cfthrow message="This is thrown to gain access to the strack trace." type="StackTrace" />
      <cfcatch>
        <cfset Trace.StackTrace = CFCATCH.StackTrace />
        <cfset Trace.TagContext = CFCATCH.TagContext />

        <!--- Add stack trace to request. --->
        <cfset ArrayAppend(REQUEST.StackTraces, Trace) />
      </cfcatch>
  </cftry>

  <cfreturn />
</cffunction>

PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

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'' =&gt; ''restrictions'', ''value'' =&gt; ''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 false;

JSP/JSTL: <% System.exit(0); %>

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-&gt;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. $@ is a variable which stores syntax errors
  }

ERROR LOGGING

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

XSLT PARAMETER PASSING

Coldfusion:
PHP:

$collections = array('Marc Rutkowski' => 'marc', 'Olivier Parmentier' => 'olivier');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

foreach ($collections as $name => $file)
  {
  // Load the XML source
  $xml = new DOMDocument;
  $xml->load('collection_' . $file . '.xml');

  $proc->setParameter('', 'owner', $name);
  $proc->transformToURI($xml, 'file:///tmp/' . $file . '.html');
  }

Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

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 &lt; 4 }
DBI.connect('DBI:Mysql:test', 'testuser', 'testpwd') do | dbh |
  dbh.select_all(query)  do | row |
    p row
  end
end

Python:

import MySQLdb as dbapi2
mysql = dbapi2.connect(database=''localhost:/tmp/mysql5.sock'',user=''myuser'',password=''mysecret'')
query = mysql.cursor()
query.execute("select * from yaddayadda")
for row in query:
    print row
query.close()
mysql.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);

PARAMETERIZED QUERIES

Coldfusion:
PHP:
Ruby:
Python:
Javascript:N/A
JSP/JSTL:
Perl:

my $sql="select name,rank,ser_no from sailors where name =:name";
my $c=$db->prepare($sql);
$c->bind_param(":name","O'Tool");
$c->execute();

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:
function include_dom(script_filename)
{
var html_doc = this.document.getElementsByTagName('head').item(0);
var js = this.document.createElement('script');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', script_filename);
html_doc.appendChild(js);
return false;
}

JSP/JSTL: <% jsp:include file=''test.JSP'' %>

Perl: use CGI

FILE ACCESS

Coldfusion:
<cffile action="read" file=''readme.txt'' variable="content">
<cfcontent type="text/plain">
<cfinclude template="test.xml">

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>;

FILE DELETION

Coldfusion:
PHP: unlink("../error.php");
Ruby:
Python:
JavaScript: N/A
JSP/JSTL:
Perl:

URL DOWNLOAD

Coldfusion:
PHP:
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "http://news.bbc.co.uk/");
$html = curl_exec ($curl);
curl_close ($curl);
Ruby:
Python:
from urllib import urlopen
page = urlopen("http://news.bbc.co.uk/").read()
Javascript:
JSP/JSTL:
Perl:

XML SERIALIZATION

Coldfusion:
PHP:

<!--XML Data-->
< ?xml version="1.0"?>
<configuration>
<entry name="path"_
value="/var/www/admin/"/>
<entry name="url"_
value="http://www.domain.be/"/>
<entry name="webmaster_
value="someEmail@address.be"/>
<entry name="lang" value="EN"/>
</configuration>

<!--XSLT File-->
< ?xml version="1.0"?>
<xsl :stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/_
1999/XSL/Transform">
<xsl :output method="text"/>
</xsl>

<!--Strip white-space-->
<xsl :variable name="total"
select="count(//entry)"/>
<!--Count all node values that we need in the PHP array.-->
<xsl :template match="/">
</xsl><xsl :text>a:</xsl>
<xsl :value-of select="$total"/>
<xsl :text>:{</xsl>
<xsl :apply-templates/>
<xsl :text>}</xsl>
<!--Start the string with the number of key/value pairs.-->
<xsl :template match="entry">
</xsl><xsl :text>s:</xsl>
<xsl :value-of_
select="string-length(@name)"/>
<!--Count the key characters.-->
<xsl :text>:"</xsl>
<xsl :value-of select="@name"/>
<xsl :text>";</xsl>
<!--Add the actual key value-->
<xsl :text>s:</xsl>
<xsl :value-of_
select="string-length(@value)"/>
<!--Count the key characters-->
<xsl :text>:"</xsl>
<xsl :value-of select="@value"/>
<xsl :text>";</xsl>

Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

DATA:URI to MHTML

Coldfusion:
PHP:

function bolk_data_uri_header()
  {
  echo "<!--\n"
  ."Content-Type: multipart/related; boundary=\"=_NextPart_01C6A9B1.539AB070\"\n\n"
  ."--=_NextPart_01C6A9B1.539AB070\n"
  ."Content-Transfer-Encoding: base64\n"
  ."Content-Type: text/html\n"
  ."-->\n\n";
  }

function bolk_data_uri($file, $style = '')
  {
  if (!(file_exists($file) && ($data = @getimagesize($file) ) ) )
    return false;

  $name = uniqid('', true);

  if ($style <> '')
    $style = ' style="'.htmlspecialchars($style).'"';

  echo "<!--\n"
  ."--=_NextPart_01C6A9B1.539AB070\n"
  ."Content-Location: {$name}\n"
  ."Content-Transfer-Encoding: base64\n"
  ."Content-Type: {$data['mime']}; -->\n"
  ."<object data='data:{$data['mime']};base64,\n\n";

  echo base64_encode(file_get_contents($file));

  echo "' {$data[3]}{$style} type='\n{$data['mime']}'><img "
  ."src='mhtml:http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}!{$name}' {$data[3]}{$style} /></object>\n\n"
  ."<!--\n"
  ."--=_NextPart_01C6A9B1.539AB070-->";

  return true;
  }

Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

FILE COMPRESSION

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

FILE ABSOLUTE PATH

Coldfusion:
PHP:
<?=
realpath('./../../etc/passwd');
?>
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

CRYPTOGRAPHY

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

JSON PARSING

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

XML PARSING

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

XSLT PROCESSING

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

DOC GENERATION

Coldfusion:
PHP:
Ruby:
Python:
Javascript:
JSP/JSTL:
Perl:

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
Review of Programming Languages
Language Design Lessons
Language Highlights
Choosing Languages
Common Programming Solutions Across Languages
Feature Comparison
Glossary of Languages
Evolutionary Languages
Scripting Language Overview
Language Categories
Language Power
Language Speed
Canonical Syntax Example
Trade Power for Flexibility
Hello World in 300 Programming Languages
Syntax of C-Derived Languages
Python vs Ruby
Python vs Lisp
What does Ruby have that Python doesn’t
AJAX vs XUL vs XAML
XAML vs CSS vs XUL vs SVG
JavaScript vs Flex vs SVG vs JSF vs ActionScript
XML Markup Languages for User Interface Definition
Syntax Comparison of XML-based UI Languages
Comparison of UI Markup Languages

Coldfusion:
CFML Reference

Objective-C
Introduction to Objective-C
Objective-C 2.0 Overview
Bridging the Gap between Java and Cocoa/
Queued Background Tasks for Cocoa/
Regular Expressions and Cocoa/

.Net Framework
.Net Framework Reference

Emacs Lisp
Emergency ELisp
Programming in Emacs Lisp
GNU Emacs Lisp Reference Manual
Debugging EmacsLisp
Learning Emacs Lisp
DotEmacs Configuration Reference
Emacs Newbie Help
Interactive HTML Development in Emacs

Python:
Official Python Tutorial
Official Python FAQ
Python Regexp Reference
Python Command Index
Python Builtin Functions
Python Exceptions
Python File System Functions
Python Reserved Method Names
Python Operator Precedence
Python Error Codes
Python Data Model
Python Lexical Analysis
Python Primer
Unix/Python Tutorial
Python Anti-FAQ
Python Object Introspection
Python Lambda Functions
The Whole Python FAQ
Text Processing in Python
Python MySQL Tutorial
Python Programming Guide
Writing Software in Python
Python Cookbook
Python Database APIs
Python Resources
Python Reference Wiki
Hands On Python
Python Programming Wiki
Unofficial Python Tutorial
Python Quick Reference
Python for System Administrators
Python for Lisp Programmers
Python for the Impatient
Python for JavaScript Programmers
Python Developer Wiki
Learn Python in 100 Lines of Code
String Formatting in Python
Python Language Notes
Instant Python
Ultra Short Python Primer
OOP in Python
Python Programmers Reference Guide
Python Syntax and Semantics
Online Python Interpreter
Online Python REPL
Try Python Online Console
Python DB-API
Python PyDoc Self-Documentation

Ruby:
Ruby and Rails API Guide
Rails Manual
Ruby Tutorials
Ruby Crash Course
Ruby Regexp Tutorial
Ruby File System Functions
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
Ruby Quick Reference
Ruby Cheat Sheet
Really Compact Ruby Guide
Ruby Programmers Reference Guide
Online Ruby Interpreter
HotRuby Online Interpreter
Ruby DBI Documentation
Ruby RDoc Self-Documentation

PHP:
PHP Language Reference
PHP Function Reference
PHP PDO Reference
PHP Operators
PHP Reserved Variables
PHP Environment Variables
PHP Predefined Constants
PHP Regexp Reference
PHP File System Functions
PHP Strings
List of Parser Tokens
PHP Function Index
PHP Programming Guide
PHP Tutorials
PHP Database API Comparison
PHP Crash Course
Using PDO with PHP/MySQL
PHP Interactive Browser Console
phpsh Interactive Shell
PHP Shell Browser Console
PHP Shell
OS X PHP Console
Client-Side PHP Interpreter
PHP Programmers Reference Guide
PHP Web Techniques
phpDocumentor Self-Documentation

Perl:
Official Perl Documentation
Perl Regexp Reference
Perl File System Functions
Perl Special Variables
CGI Perl Module Guide
Modular Perl Guide
Object Oriented Perl Guide
Object Oriented Perl
Perl 101
Perl Quick Reference
Lessons in Perl
Perl Phrasebook
Perl Lexical Structure, Syntax and Operators
Perl Programmers Reference Guide
Advanced Perl DBI
Cookies in Perl
Perl DBI Documentation
Perl Console Interactive Shell
Client-Side Perl Interpreter
Devel-REPL Interactive Shell
Perl POD Self-Documentation

JavaScript:
JavaScript Language Reference
JavaScript Guide
JScript Language Reference
Sitepoint JavaScript Reference
JavaScript Guide
Naked JavaScript Objects
JavaScript Regexp Tutorial
JavaScript Date Object
XMLHTTP Reference
Javascript Programming Guide
Unofficial JavaScript Tutorial
JavaScript from Scratch
JavaScript Unicode Escape Sequences
JavaScript Regex and Unicode Tests
JavaScript Tokens
JavaScript Punctuators
JavaScript Lexical Structure
AJAX Tutorial
SVG DOM Reference
JavaScript Programmer's Reference
Documenting JavaScript with JSDoc
Using JSDoc tags for organizing CSS
Using Inline Doc Comments with JsDoc-Toolkit
YUI Doc
JavaScript Shell Browser Console

ActionScript 3:
Actionscript 3.0 Programming Guide
Actionscript 3.0 Reference
Flash Actionscript Docs

ActionScript 2:
Actionscript 2.0 Reference
Actionscript 2.0 Dictionary
Actionscript 2 Tutorials
Industrial Strength Actionscript Hacks

ActionScript 1:
Actionscript Dictionary
Actionscript Developer Guide

JSP/JSTL:
JSP Tutorial
JSP API Documentation
JSP and Servlet API Reference
JSP and Servlets Best Practices
JSP and Servlets Quick Reference
JSP2.0 Syntax Reference
JSP Documents
JSP2.0 XML Cheat Sheet
JSP Error Pages and Preventing Repeated Operations
JSP Blog
Unified Expression Language
JSTL Primer, Pt. 1
JSTL Primer, Pt. 2
JSTL Expression Language Overview
JSTL Environment Variables
JSTL Functions
JSTL Tutorial
JSTL 1.1 Documentation
Summary of What to Know about Servlets
Servlet Development using Tomcat
JSP Development using Tomcat
Servlet Environment Variables
Servlet Quick Guide
Struts API Reference
Searching for Code in J2EE AJAX Applications

Character Sets and Entities:
HTML and Unicode Punctation and Symbol Codes
Greek Alphabet and Symbol Entities
Text Escaping and Unescaping
Named HTML Entities in Alphabetical Order
Numeric HTML Character Entities
International Character Sets
Handling UTF-8
How to find the entity number for a Unicode character and vice versa
HTML Special Characters
HTML Entities
New Line Code (HTML, Java, URL & Escape Sequence)
MIME Types
Complete List of MIME Types
List of Common MIME Types
MIME Type Quick Reference
MIME Types Grouped by Category
The MIME Multipart/Related Content-type
Content-ID and Message-ID Uniform Resource Locators
MIME Encapsulation of Aggregate Documents, such as HTML

Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.