Action
Perl
Python
PHP
JavaScript
PowerShell
1. Variables




Strings my $s = "Hello world"; s = "Hello world" $s = "Hello world"; var s = "Hello world"; [string]$s = "hello world"
Numbers my $n = 5;
n = 5
$n = 5;
var n = 5;
[int]$n = 5
Arrays / lists my @letters = ("a", "b", "c"); letters = ["a", "b", "c"] $letters = array("a", "b", "c"); var letters = ["a", "b", "c"]; $letters = @("a", "b", "c")
Element from an array my $a = $letters[0]; a = letters[0] $a = $letters[0]; var a = letters[0]; $a = $letters[0]
Associative arrays / hashes my %info = ("name", "John", "age", 28); info = {"name": "John", "age": 28} $info = ["name" => "John", "age" => 28]; var info = {name: "John", age: 28}; $info = @{ "name" = "John"; "age" = 28 }
Print to standard output print "Hello " . $info{"name"} . "\n"; print("Hello " + str(info["name"])) echo "Hello " . $info["name"] . "\n"; document.write("Hello " + info["name"]); Write-Host "Hello $($info.name)"
Read from standard input print "Enter your name: ";
$myname = readline STDIN;
myname = input("Enter your name: ") echo "Enter your name: ";
$myname = fgets(STDIN);
var $myname =
document.getElementsByName("name")[0].value;
$name = Read-Host "Enter your name"
Int to string $s = "" . $n; s = str(n) $s = strval($n); var s = n.toString(); $s = [string]$n
String to int $t = int($s); t = int(s) $t = intval($s); var t = parseInt(s); $t = [Int32]$s
2. String operations




Multi-line strings my $s = <<'EOF';
Hello
world.
EOF
s = """
Hello
world."""
$s = <<<EOF
Hello
world.
EOF;
var s = "\
Hello\
world."
$s = @'
Hello
world.
'@
Concatenation my $string1 = "Hello ";
my $result = $string1 . "world\n";
string1 = "Hello "
result = string1 + "world\n"
$string1 = "Hello ";
$result = $string1 . "world\n";
var string1 = "Hello ";
var result = string1 + "world\n";
$string1 = "Hello ";
$result = $string1 + "world`n";
Remove trailing newline chomp($result); result = result.rstrip("\n") $result = rtrim($result, "\n") result = result.slice(0,-1) $result = $result.TrimEnd()
String length
print length($result);
print(len(result))
echo strlen($result); document.write(result.length); $result.Length
Sub string my $result = substr($string, $start, $length); result = string[start:end] $result = substr($string, $start, $length); var result = string.substr(start, length); $result = $result.SubString($start, $end)
Test for sub string if(index($result, "o") != -1) { ... } if "o" in result:
...
if(strpos($result,"o") !== false) { ... } if(result.indexOf("o") != -1) { ... } if($result -Match "o") { ... }
Replace sub string $result =~ s/world/planet/g; result = str.replace(result, "world",
"planet");
$result = str_replace("world", "planet",
result);
result = result.replace("world", "planet"); $result = $result -Replace "world","planet"
To upper case print uc($result); print(result.upper()) echo strtoupper($result); document.write(result.toUpperCase());
$result.ToUpper()
Array to string my $result = join(" ", @letters);
result = " ".join(letters)
$result = implode(" ", $letters); var result = letters.join(" "); $result = $letters -join " "
String to array my @results = split(/ /, $result); results = result.split() $results = explode(" ", $result); var results = result.split(" "); $results = $result -split " "
Add element to array push(@letters, "d"); letters.append("d") $letters[] = "d"; letters.push("d"); $letters += "d"
Remove last element
pop(@letters);
letters.pop() array_pop($letters); letters.pop(); $letters = $letters | Where {$_ -ne "d"}
Remove first element shift(@letters); letters.pop(0) array_shift($letters); letters.shift(); $letters = $letters | Where {$_ -ne "a"}
Convert to Base64use MIME::Base64;
my $enc = encode_base64($result, "");
import base64
enc = base64.b64encode(result.encode('utf-8'))
$enc = base64_encode($result);var enc = window.btoa(result); [byte[]]$b = [System.Text.Encoding]::UTF8.GetBytes($result)
$enc = [System.Convert]::ToBase64String($b)
3. Loops




For each item of a list foreach my $letter (@letters)
{
print $letter;
}
for letter in letters:
print(letter)
foreach($letters as $letter)
{
echo $letter;
}
letters.forEach(function(letter)
{
document.write(letter);
});
foreach ($letter in $letters)
{
$letter
}
While loop while($n > 0)
{
$n--;
}
while n > 0:
n -= 1
while($n > 0)
{
$n--;
}
while(n > 0)
{
n--;
}
while($n -gt 0)
{
$n--
}
For loop for($i = 0; $i < 10; $i++)
{
print $i;
}
for i in range(10):
print(i)
for($i = 0; $i < 10; $i++)
{
echo $i;
}
for(i = 0; i < 10; i++)
{
document.write(i);
}
for($i=0;$i -lt 10; $i++)
{
$i
}
If if($a eq "a")
{
print "The letter A";
}
if a == "a":
print("The letter A")
if($a == "a")
{
echo "The letter A";
}
if(a == "a")
{
document.write("The letter A");
}
if($a -eq "a")
{
$a
}
Else if elsif($a eq "b")
{
print "The letter B";
}
elif a == "b":
print("The letter B")
else if($a == "b")
{
echo "The letter B";
}
else if(a == "b")
{
document.write("The letter B");
}
elseif($a -eq "b")
{
$a
}
Else else
{
print "Some other letter";
}
else:
print("Some other letter")
else
{
echo "Some other letter";
}
else
{
document.write("Some other letter");
}
else
{
"Some other letter"
}
4. Functions




Defining a function sub add_values
{
my ($x, $y) = @_;
return $x + $y;
}
def add_values(x, y):
return x + y
function add_values($x, $y)
{
return $x + $y;
}
function add_values(x, y)
{
return x + y;
}
function add_values([int32]$a, [int32]$b)
{
return $a + $b
}
Calling a function
my result = add_values(2, 5);
result = add_values(2, 5) $result = add_values(2, 5); var result = add_values(2, 5); $result = add_values 2 5
Adding a module use XML::Feed; import xmltodict include "xml_functions.php"; <script src="xml_functions.js"></script> Import-Module my-module
5. File operations




Open a file for reading open(F, "file.txt"); f = open("file.txt", "r") $f = fopen("file.txt", "r"); var f = new XMLHttpRequest();
f.open("GET", "file://file.txt", false);
-
Read from a file while(my $line = <F>)
{
print $line;
}
for line in f:
print(line)
while(!feof($f))
{
echo fgets($f);
}
f.onreadystatechange = function()
{
if(f.readyState === 4)
{
document.write(f.responseText);
}
}
f.send(null);
Get-Content file.txt
Open a file for writing open(F, ">file.txt"); f = open("file.txt", "w") $f = fopen("file.txt", "w"); --
Write to a file print F "Hello world"; f.write("Hello world") fwrite($f, "Hello world"); -"Hello world" | Out-File file.txt
Close a file close(F); f.close() fclose($f); --
Check if a file exists if(-e "file.txt")
{ ... }
import os.path
if os.path.exists("file.txt"):
...
if(file_exists("file.txt"))
{ ... }
-Test-Path .\file.txt
Show current folder use Cwd;
print Cwd::cwd();
import os
print(os.getcwd())
echo getcwd(); document.write(document.URL); console: (Get-Location).Path
script: $PSScriptRoot
Make a folder mkdir("mydir");
import os
os.mkdir("mydir")
mkdir("mydir"); -mkdir mydir
6. Database connections




Connect to MySQL use DBI;
$db = DBI->connect("dbi:mysql:database=mysql;
host=localhost;", $user, $pass);
import pymysql
db = pymysql.connect(host="localhost",
user="user", passwd="pass", db="mysql")
$db = new PDO("mysql:host=localhost;
dbname=mysql", $user, $pass);
--
Connect to SQLite use DBI;
$db = DBI->connect("dbi:SQLite:dbname=file.db");
import sqlite3
db = sqlite3.connect("file.db")
$db = new PDO("sqlite:file.db"); var db;
var con = indexedDB.open("mydb", 1);
con.onupgradeneeded = function(e)
{
var a = e.target.result;
if(!a.objectStoreNames.contains("users"))
{ a.createObjectStore("users"); }
}
con.onsuccess = function(e)
{ db = e.target.result; }
See: sqlite_powershell.md
Query the database $sql = $db->prepare("SELECT * FROM users WHERE
name=?");
$sql->execute($name);
while (my @res = $sql->fetchrow_array())
{
print($res[1]);
}
sql = db.cursor()
sql.execute("SELECT * FROM users WHERE
name=:a", {"a": name})
db.commit()
f = sql.fetchall()
for i in f:
print(i[1])
$sql = $con->prepare("SELECT * FROM users");
$sql->execute();
foreach($sql->fetchAll() as $row) { ... }
var sql = db.transaction(["users"],
"readonly");
var store = sql.objectStore("users");
var req = store.get(name);
req.onsuccess = function(e)
{ document.write(e.target.result); }
See: sqlite_powershell.md
Insert data $sql = $db->prepare("INSERT INTO users VALUES
(?, ?)");
$sql->execute($name, $age);
sql = db.cursor()
sql.execute("INSERT INTO users VALUES
(:a, :b)", {"a": name, "b": age})
db.commit()
$sql = $db->prepare("INSERT INTO users
VALUES (?, ?)");
$sql->execute(array($name, $age));
var sql = db.transaction(["users"],
"readwrite");
var store = sql.objectStore("users");
var req = store.add(age, name);
See: sqlite_powershell.md
Close the connection $db->disconnect; db.close() --
See: sqlite_powershell.md
7. Web and networking




HTML form queries use CGI;
$query = new CGI;
print $query->param("name");
import cgi
form = cgi.FieldStorage()
print(form["name"].value)
echo $_GET["name"];
echo $_POST["name"];
document.write(document.getElementsByName(
"name")[0].value);
-
Set a cookie use CGI::Cookie;
$c = CGI::Cookie->new(-name=>"name",
-value=>"John Doe");
print header(-cookie=>[$c, ...]);
from http import cookies
c = cookies.SimpleCookie()
c['name'] = "John Doe"
print(c)
setcookie("name", "John Doe"); document.cookie="name=John Doe"; -
Read a cookie %cookies = CGI::Cookie->fetch;
$name = $cookies{"name"}->value;
import os
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for cookie in cookies:
cookie = cookie.split('=')
c[cookie[0]] = cookie[1]
name = c['name']
$name = $_COOKIE['name']; var cookies = document.cookie.split(';');
for(var i=0; i<cookies.length; i++)
{
var c = cookies[i];
while (c.charAt(0)==' ')
{ c = c.substring(1); }
if (c.indexOf("name=") != -1)
{ var name =
c.substring("name=".length, c.length); }
}
-
Fetch a web page use LWP::Simple;
print get($url);
import urllib.request
response = urllib.request.urlopen(url)
print(response.read())
echo file_get_contents($url); var req = new XMLHttpRequest();
req.open('GET', url, false);
req.send(null);
document.write(req.responseText);
Invoke-WebRequest -Uri $url
RSS / HTML parsing use XML::Feed;
use HTML::FormatText::WithLinks;
my $f = XML::Feed->parse(URI->new($FEED));
foreach my $i ($f->entries)
{
print "\nTitle: " . $i->title . "\n";
print "Time: " . $i->issued . "\n";
print "Link: " . $i->link . "\n";
$parsed = HTML::FormatText::WithLinks->new
(before_link=>'', after_link=>'', footnote=>'');
print $parsed->parse($i->content->body) . "\n";
}
import feedparser
from bs4 import BeautifulSoup
f = feedparser.parse(FEED)
for i in f['entries']:
print("\nTitle: {0}".format(i['title']))
print("Time: {0}".format(i['issued']))
print("Link: {0}".format(i['link']))
print(BeautifulSoup(i['description'])
.get_text())
$f = simplexml_load_file($FEED);
foreach($f->channel->item as $i)
{
echo "\nTitle: " . $i->title . "\n";
echo "Date: " . $i->pubDate . "\n";
echo "Link: " . $i->link . "\n";
echo convert_html_to_text
($i->description) . "\n";
}
$.get(FEED, function (f)
{
$(f).find("item").each(function()
{
var i = $(this);
document.write("Title: " +
i.find("title").text());
document.write("Date: " +
i.find("pubDate").text());
document.write("Link: " +
i.find("link").text());
document.write(i.find("description")
.text());
}); });
[xml]$a = Invoke-WebRequest -Uri https://reddit.com/.rss
$a.rss.channel.item| Select title,pubdate,link
Parse JSON use JSON::Parse 'parse_json';
my $parsed = parse_json($result);
$status = $parsed->{'status'};
import json
parsed = json.loads(result)
status = parsed['status']
$parsed = json_decode($result);
$status = $parsed->{'status'};
var parsed = JSON.parse(result);
var status = parsed.status;
$a.Content | ConvertFrom-Json
8. Date and numbers




Random number print int(rand(100)); import random
print(random.randrange(0, 100))
echo rand(0, 100); document.write(parseInt(Math.random()
* 100));
Get-Random -Minimum 0 -Maximum 100
Current date use DateTime;
print(DateTime->today());
from datetime import date
print(date.today())
echo date(DATE_RFC2822); document.write(Date()); Get-Date
Unix / Epoch time print time(); import time
print(int(time.time()))
echo time(); document.write(Date.now()); [int32](Get-Date -UFormat %s)
9. Misc




Error handling eval { ... } or do { print $@; }; import sys
try:
...
except:
a, b, c = sys.exc_info()
print(str(b))
try { ... }
catch(Exception $e)
{
echo $e->getMessage();
}
try { ... }
catch(e)
{
document.write(e.message);
}
try { ... }
catch(Exception $e)
{
$e
}
Command line arguments foreach my $arg (@ARGV)
{
print $arg . "\n";
}
import sys
for arg in sys.argv:
print(arg)
foreach($argv as $arg)
{
echo $arg . "\n";
}
var items = location.search; param([string]$a, [int32]%b)
System execute system("ls -l"); import subprocess
subprocess.call(["ls", "-l"], shell=True)
exec("ls -l"); -dir
Pause script sleep(5); import time
time.sleep(5)
sleep(5); window.setTimeout(function_name, 5000); sleep(5)
SHA-1 hash use Digest::SHA qw(sha1_hex);
print sha1_hex("test");
import hashlib
print(hashlib.sha1(b"test").hexdigest())
echo sha1("test"); <script
src="http://crypto-js.googlecode.com/svn
/tags/3.0.2/build/rollups/hmac-sha1.js">
</script><script>
document.write(CryptoJS.SHA1("test"));
</script>
$sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider
$enc = [system.Text.Encoding]::UTF8
$b = $enc.GetBytes("Hello world")
$result = ""; $sha.ComputeHash($b) |foreach { $result += $_.ToString("X2") }; $result
Module installation perl -MCPAN -e 'install module' python -m pip install module pear install module <script src="module.js"></script>