Equivalents in JavaScript and Perl

DSC_4026

This page is a list of similarities between Perl and JavaScript to help go 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 Perl keywords go to perldoc.perl.org. Most of the JavaScript keywords are linked to w3schools.com, but where that site doesn't cover something, the links go to the Mozilla Developers' Network page.

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) parseInt('0x'+str)
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)
+
concat
String concatenation is via "." in Perl, but "+" in JavaScript. JavaScript also uses "+" for addition of numbers.
sprintf, printf
×
JavaScript has no equivalent.
$str x $n
str.repeat(n)
substr ($str, $n, 1)
str.charAt(n)
$str =~ /\Q$end$/
str.endsWith(end)
Perl does not have an equivalent function.
$str =~ /^\Q$begin\E/
str.startsWith(begin)
Perl does not have an equivalent function.
$str =~ /\Q$included\E/
str.includes(included)
Perl does not have an equivalent function.
$str =~ s/^\s+|\s+$//g
str.trim ()
Perl does not have an equivalent function, although it is found in several modules, such as Data::Munge.
Regexes
🐪 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)
quotemeta
×
JavaScript does not have an equivalent.
pos str
regex.lastIndex ()
In JavaScript, the position is associated with a regex rather than a string.
Hashes / objects
🐪 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.
@all_keys = keys %hash
all_keys = Object.keys (hash)
Object.values appeared first in ECMAScript version 5.1. See the next entry for how to loop over keys of a hash in JavaScript.
for my $i (keys %hash) { }
for (var i in hash)
These loop over all the keys in a hash (associative array).
values (%hash)
Object.values (hash)
Object.values appeared first in ECMAScript 2017 Draft. It is currently "experimental".
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)
push @arr, @otherarr
arr.push (otherarr)
@finalarr = (@arr, @otherarr)
finalarr = arr.concat (otherarr)
Perl doesn't have a special function for this.
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
map
Until ECMA version 5, this used to have no equivalent in JavaScript. The JavaScript library jQuery supplies an equivalent to Perl's map.
grep
×
This has no equivalent in JavaScript. The JavaScript library jQuery supplies an equivalent to Perl's grep.
x
×
JavaScript has repeat for strings.
"@array"
array.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.
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.
$x**$y
Math.pow(x, y)
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.
sprintf ("%.0f", $_), POSIX round
Math.round ()
Perl doesn't have a standard way of rounding numbers.
link, socket, mkdir, and anything else to do with files, sockets, processes, etc.
×
Originally JavaScript did not have equivalents because JavaScript was 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.
URI::Escape uri_escape
escape
encodeURI
Perl does not have a built-in equivalent.
URI::Escape uri_unescape
unescape
decodeURI
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
There is no switch in Perl.
Variables and values
🐪 Perl
🍳 JavaScript
🎵 Notes
my
var, let
JavaScript now also includes "let" for defining variables. "let" is much closer to Perl's "my" than "var", which has lots of weird properties.
use constant c => 1
const c = 1;
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.
'Inf', '-Inf'
Infinity, -Infinity
See Special floating point: infinity (Inf) and not-a-number (NaN) in perldata.
'NaN'
NaN
Dynamic document creation
🐪 Perl
🍳 JavaScript
🎵 Notes
open
doc=Window.open
doc.open
close
doc.close
print
document.write
console.log
Writes to the current document in JavaScript, to STDOUT (the default filehandle) in Perl. console.log writes to the console in JavaScript.
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-2021. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. News about the site. / Privacy / Disclaimer