Equivalents in JavaScript and Perl

DSC_4026

This list of similarities between Perl and JavaScript is meant to help programmers get started going from one language to the other.

Bold face indicates an argument or optional element. The × symbol means that something is not available. For example, JavaScript has no equivalent to Perl's quotemeta.

The links on the keywords go to perldoc.perl.org for the Perl keywords, and to w3schools.com for JavaScript.

Strings
Perl JavaScript Notes
uc $str str.toUpperCase ()
lc $str str.toLowerCase ()
ucfirst $str
lcfirst $str
× JavaScript has no equivalent single functions for these.
int $str parseInt (str)
hex $str parseInt(str,16) Convert a string to a number as if the string is hexadecimal.
ord $str str.charCodeAt(0)
ord (substr $str, n, 1) str.charCodeAt(n)
chr $number String.fromCharCode(number) In the JavaScript, the "String" is part of the function call, like the "Math" in "Math.sin". It is not a variable.
sprintf ("%X", $number) number.toString (16) Make hexadecimal strings from a number.
split str/regex $str str.split (str/regex)
substr $string, offset, length str.substr (offset, length)
str.substring (start, end)
index $str, something str.indexOf (something)
index ($str, something, -1)
rindex ($str, something)
str.lastIndexOf(something) Find the last occurence of something in str
length $str str.length Length of a string
$str =~ tr/abc/xyz/ × Perl's "tr" has no equivalent in JavaScript.
. (Concatenation operator) + String concatenation is via "." in Perl, but "+" in JavaScript. JavaScript also uses "+" for addition of numbers.
sprintf, printf × JavaScript has no equivalent.
Regular expressions (regexs, regexps)
Perl JavaScript Notes
$str =~ s/regex/y/ str.replace (/regex/, y)
$str =~ s/regex/function ($1, $2)/e str.replace (/regex/, function (match, first, second) { code } ) The JavaScript "replace" can take a function as the second argument. This function takes the matched text as its argument, followed by the match of each pair of brackets (like Perl's $1, $2, etc.) and its return value is inserted into the string. See ECMAScript specification 15.5.4.11.
$str =~ m/regex/ str.match (/regex/)
regex.test (str)
$str =~ s/regex/y/g str.replace (/regex/g, y)
str.replace (/regex/, y, "g")
In Mozilla's version of JavaScript, arguments like "g" for global replacement, or "i" for case insensitivity, can be added after the slashes or as a third argument. However, this is not part of the ECMA standard.
quotemeta × JavaScript does not have an equivalent.
pos str regex.lastIndex () In JavaScript, the position is associated with a regex rather than a string.
Associative arrays (hashes)
Perl JavaScript Notes
my %hash var hash=new Object() JavaScript's objects function as hashes.
my %hash = (a => "b", c => "d") var hash = {"a" : "b", "c" : "d"}
$hash{key} hash[key]
hash.key
Access hash keys using the [ ] or . notation in JavaScript.
keys in See next entry.
for my $i (keys %hash) { } for (var i in hash) These loop over all the keys in a hash (associative array).
values × Perl's "values" has no equivalent in JavaScript
defined $variable typeof (variable) != "undefined"
delete $hash{key} delete hash[key]
exists × JavaScript has no equivalent.
Arrays
Perl JavaScript Notes
my @arr = () var arr = new Array ()
my @arr = ('hot', 'cold') var arr = new Array ("hot", "cold")
@arr = qw/cat fish dog/ arr = "cat fish dog".split (/\s+/)
pop @arr arr.pop Most of JavaScript's array operators seem to have been based on Perl and have the same names.
push @arr, $value arr.push (value)
reverse @arr arr.reverse
splice @arr, offset, length arr.splice (offset, length)
sort @arr arr.sort
sort {some code} @arr arr.sort (some function) These sort using a user-defined method of comparing.
join str, @arr arr.join (str) These join the elements of an array together.
scalar @arr
$#arr + 1
arr.length These functions give the number of elements in an array
map, grep × These have no equivalent in JavaScript. The JavaScript library jQuery supplies an equivalent to Perl's map.
Specific functions
Perl JavaScript Notes
sin, cos, exp, etc. Math.sin, Math.cos, Math.exp, etc. Both JavaScript and Perl use the same names for their mathematical functions as C. JavaScript puts "Math." before each function name.
rand Math.random () Unlike most of the maths functions, neither of these is like the C functions rand or random. They both return a number between 0 and 1.
link, socket, mkdir, and anything else to do with files, sockets, processes, etc. × JavaScript does not have equivalents because JavaScript is only meant to run inside a web browser.
warn alert
print "Answer: ";
$str = <STDIN>;
$str = "default" unless $str;
str = prompt ("Answer: ", "default"); The Perl example is a command-line equivalent.
× object.toString Perl does not have an explicit equivalent (convert any object into a string). However, arrays, strings, and numbers are automatically converted into strings in a print context.
URI::Escape uri_escape escape
encodeURI
Perl does not have a built-in equivalent.
URI::Escape uri_unescape unescape
decodeURI
Perl does not have a built-in equivalent.
MIME::Base64 encode_base64 btoa atob and btoa are not part of any JavaScript standard. They will work on most implementations except older versions of Internet Explorer.
MIME::Base64 decode_base64 atob
ualarm (from core module Time::HiRes) setTimeout
Program control
Perl JavaScript Notes
exit throw (exception) JavaScript has no function to halt execution.
die throw (exception)
next continue JavaScript uses the same names as C, C++, and Java for loop control.
last break
ref typeof
wantarray × JavaScript has no equivalent.
eval { code } try/catch
eval $str eval
goto × JavaScript has no "goto".
return return
sub function Perl does not have "functions", and JavaScript does not have subroutines, although each of these commands does both jobs.
caller function.caller.toString()
arguments.callee.caller.toString()
function is the name of the current function.
bless new In Perl, bless is called to register an object's type after it has been created. Perl modules often have a "new" function, but this is not part of Perl - the "new" function could be called anything. "bless", however, is part of Perl.
Module::function ($object) function.call (object) Here function is the name of the function and Module is the name of the Perl module. $object in Perl is an instance of Module.
× switch Perl version 5.10 introduced "given" and "when", which serves the same purpose.
Variables and values
Perl JavaScript Notes
my var
undef, 0, an empty string false Perl does not have booleans
Any value except 0, a string of length zero, or the special value undef. true
$_ × JavaScript has no equivalent to Perl's $_.
$a, $b × JavaScript has no equivalent to Perl's $a and $b. A function argument to sort is assumed to have two arguments.
@ARGV × JavaScript has no equivalent to Perl's @ARGV.
@_ arguments JavaScript's "arguments" also functions similarly to Perl's caller.
$1, $2, $3, etc. $1, $2, $3, etc.
$x = qr/regex/ x = new RegExp (regex)
\ (reference operator) × JavaScript has no equivalent.
Dynamic document creation
Perl JavaScript Notes
JavaScript cannot open files but it can open windows. Here are some similar commands from JavaScript and Perl.
open doc=Window.open
doc.open
close doc.close
print document.write Writes to the current document in JavaScript, to STDOUT (the default filehandle) in Perl.
print FH doc.write Print to a particular document doc in JavaScript, a particular file handle FH in Perl.
say document.writeln In Perl 5.10, "say" is the same as "print" except that it appends a new line character after what it has printed. JavaScript's "writeln" and "write" have the same relationship.

Web links


Copyright © Ben Bullock 2009-2014. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer