<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<link rel="icon" type="image/gif" href="favicon.gif"/>
<link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png" />
<link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png" />
<title>Scripting Languages II: Perl, Lua, Groovy - Hyperpolyglot</title>
<style type="text/css" id="internal-style">
@import url(hyperpolyglot.css);
</style>
<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<meta http-equiv="content-language" content="en"/>
</head>
<body>
<div id="container-wrap-wrap">
  <div id="container-wrap">
    <div id="container">
      <div id="header">
        <h1><a href="index.html"><span>Hyperpolyglot</span></a></h1>
      </div>
      <div id="content-wrap">
        <div id="main-content">
<div id="page-title">
                            Scripting Languages II: Perl, Lua, Groovy
                        </div>
<div id="page-content">
                        

<p><a name="top" id="top"></a><em>a side-by-side reference sheet</em></p>
<p><a href="more#grammar-invocation">grammar and execution</a> | <a href="more#variables-expressions">variables and expressions</a> | <a href="more#arithmetic-logic">arithmetic and logic</a> | <a href="more#strings">strings</a> | <a href="more#regexes">regexes</a> | <a href="more#dates-time">dates and time</a> | <a href="more#arrays">arrays</a> | <a href="more#dictionaries">dictionaries</a> | <a href="more#functions">functions</a> | <a href="more#execution-control">execution control</a> | <a href="more#exceptions">exceptions</a> | <a href="more#streams">streams</a> | <a href="more#files">files</a> | <a href="more#file-fmt">file formats</a> | <a href="more#directories">directories</a> | <a href="more#processes-environment">processes and environment</a> | <a href="more#option-parsing">option parsing</a> | <a href="more#libraries-namespaces">libraries and namespaces</a> | <a href="more#objects">objects</a> | <a href="more#inheritance-polymorphism">inheritance and polymorphism</a> | <a href="more#reflection">reflection</a> | <a href="more#net-web">net and web</a> | <a href="more#unit-tests">unit tests</a> | <a href="more#debugging-profiling">debugging and profiling</a></p>
<table class="wiki-content-table">
<tr>
<th><a name="general" id="general"></a></th>
<th><a href="more#perl">perl</a></th>
<th><a href="more#lua">lua</a></th>
<th><a href="more#groovy">groovy</a></th>
</tr>
<tr>
<td><a name="version-used" id="version-used"></a><a href="more#version-used-note">version used</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td><span style="color: gray"><em>5.18</em></span></td>
<td><span style="color: gray"><em>5.1</em></span></td>
<td><span style="color: gray"><em>2.3</em></span></td>
</tr>
<tr>
<td><a name="show-version" id="show-version"></a><a href="more#show-version-note">show version</a></td>
<td>$ perl <span style="white-space: pre-wrap;">--</span>version</td>
<td>$ lua -v</td>
<td>$ groovy -v</td>
</tr>
<tr>
<td><a name="implicit-prologue" id="implicit-prologue"></a><a href="more#implicit-prologue-note">implicit prologue</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>use strict;</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="grammar-execution" id="grammar-execution"></a><a href="more#grammar-execution-note">grammar and execution</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="interpreter" id="interpreter"></a><a href="more#interpreter-note">interpreter</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>$ perl foo.p</td>
<td>$ lua foo.lua</td>
<td>$ echo 'println "hi!"' &gt; hi.groovy<br />
$ groovy hi.groovy</td>
</tr>
<tr>
<td><a name="repl" id="repl"></a><a href="more#repl-note">repl</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>$ perl -de 0</td>
<td>$ lua</td>
<td>$ groovysh</td>
</tr>
<tr>
<td><a name="cmd-line-program" id="cmd-line-program"></a><a href="more#cmd-line-program-note">command line program</a></td>
<td>$ perl -e 'print("hi\n")'</td>
<td>$ lua -e 'print("hi world!")'</td>
<td>$ groovy -e 'println "hi world!"'</td>
</tr>
<tr>
<td><a name="block-delimiters" id="block-delimiters"></a><a href="more#block-delimiters-note">block delimiters</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>{}</td>
<td>do end</td>
<td>{}</td>
</tr>
<tr>
<td><a name="stmt-separator" id="stmt-separator"></a><a href="more#stmt-separator-note">statement separator</a></td>
<td>;</td>
<td><span style="color: gray"><em>newline or</em> ;</span><br />
<br />
<span style="color: gray"><em>newline not separator inside {}, (), or after binary operator.<br />
<br />
newline can be put in "" or '' if preceded by backslash</em></span></td>
<td><span style="color: gray"><em>newline or</em> ;</span><br />
<br />
<span style="color: gray"><em>newline not a separator inside (), [], triple quote literal, or after binary operator or backslash.</em></span></td>
</tr>
<tr>
<td><a name="expr-stmt" id="expr-stmt"></a><a href="more#expr-stmt-note">are expressions statements</a></td>
<td></td>
<td><span style="color: gray"><em>no</em></span></td>
<td><span style="color: gray"><em>yes</em></span></td>
</tr>
<tr>
<td><a name="source-code-encoding" id="source-code-encoding"></a><a href="more#source-code-encoding-note">source code encoding</a></td>
<td>use utf8;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="eol-comment" id="eol-comment"></a><a href="more#eol-comment-note">end-of-line comment</a></td>
<td><span style="color: gray"># comment</span></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">--</span> comment</span></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> comment</span></td>
</tr>
<tr>
<td><a name="multiple-line-comment" id="multiple-line-comment"></a><a href="more#multiple-line-comment-note">multiple line comment</a></td>
<td><span style="color: gray">=for<br />
comment line<br />
another line<br />
=cut</span></td>
<td><span style="white-space: pre-wrap;">--</span>[[<br />
<span style="white-space: pre-wrap;">  </span><span style="color: gray"><em>commented out</em></span><br />
<span style="white-space: pre-wrap;">  </span><span style="color: gray"><em>also commented out</em></span><br />
]]</td>
<td><span style="color: gray">/* comment<br />
another comment */</span></td>
</tr>
<tr>
<th colspan="4"><a name="variables-expressions" id="variables-expressions"></a><a href="more#variables-expressions-note">variables and expressions</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="local-var" id="local-var"></a><a href="more#local-var-note">local variable</a></td>
<td>my $v;<br />
my (@a, %d);<br />
my $x = 1;<br />
my ($y, $z) = (2, 3);</td>
<td>local x = 1</td>
<td>x = 1<br />
def y = 2<br />
Integer z = 3</td>
</tr>
<tr>
<td><a name="local-scope-region" id="local-scope-region"></a><a href="more#local-scope-region-note">regions which define lexical scope</a></td>
<td>top level:<br />
<span style="white-space: pre-wrap;">  </span>file<br />
<br />
nestable:<br />
<span style="white-space: pre-wrap;">  </span>function body<br />
<span style="white-space: pre-wrap;">  </span>anonymous function body<br />
<span style="white-space: pre-wrap;">  </span>anonymous block</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="global-var" id="global-var"></a><a href="more#global-var-note">global variable</a></td>
<td>our ($g1, $g2) = (7, 8);<br />
<br />
sub swap_globals {<br />
<span style="white-space: pre-wrap;">  </span>($g1, $g2) = ($g2, $g1);<br />
}</td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">--</span> assign without using local</span><br />
g = 1<br />
<br />
function incr_global()<br />
<span style="white-space: pre-wrap;">  </span>g = g + 1<br />
end</td>
<td></td>
</tr>
<tr>
<td><a name="const" id="const"></a><a href="more#const-note">constant</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>use constant PI =&gt; 3.14;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="assignment" id="assignment"></a><a href="more#assignment-note">assignment</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>$v = 1;</td>
<td>x = 1</td>
<td>x = 1</td>
</tr>
<tr>
<td><a name="parallel-assignment" id="parallel-assignment"></a><a href="more#parallel-assignment-note">parallel assignment</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>($x, $y, $z) = (1, 2, 3);<br />
<br />
<span style="color: gray"># 3 is discarded:</span><br />
($x, $y) = (1, 2, 3);<br />
<br />
<span style="color: gray"># $z set to undef:</span><br />
($x, $y, $z) = (1, 2);</td>
<td>x, y, z = 1, 2, 3<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">--</span> 3 is discarded:</span><br />
x, y = 1, 2, 3<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">--</span> z is set to nil:</span><br />
x, y, z = 1, 2</td>
<td>(x, y, z) = [1, 2, 3]<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> 3 is discarded:</span><br />
(x, y) = [1, 2, 3]<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> z is set to null:</span><br />
(x, y, z) = [1, 2]</td>
</tr>
<tr>
<td><a name="swap" id="swap"></a><a href="more#swap-note">swap</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>($x, $y) = ($y, $x);</td>
<td>x, y = y, x</td>
<td>(x, y) = [y, x]</td>
</tr>
<tr>
<td><a name="compound-assignment" id="compound-assignment"></a><a href="more#compound-assignment-note">compound assignment</a><br />
<span style="color: gray"><em>arithmetic, string, logical, bit</em></span></td>
<td>+= -= *= /= %= **=<br />
.= x=<br />
&amp;&amp;= <span style="white-space: pre-wrap;">||=</span> ^=<br />
<span style="white-space: pre-wrap;">&lt;&lt;= &gt;&gt;=</span> &amp;= |= ^=</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="incr-decr" id="incr-decr"></a><a href="more#incr-decr-note">increment and decrement</a></td>
<td>my $x = 1;<br />
my $y = ++$x;<br />
my $z = <span style="white-space: pre-wrap;">--</span>$y;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="null" id="null"></a><a href="more#null-note">null</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>undef</td>
<td>nil</td>
<td>null</td>
</tr>
<tr>
<td><a name="null-test" id="null-test"></a><a href="more#null-test-note">null test</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>! defined $v</td>
<td>v == nil</td>
<td>v == null</td>
</tr>
<tr>
<td><a name="undef-var" id="undef-var"></a><a href="more#undef-var-note">undefined variable access</a></td>
<td><span style="color: gray"><em>error under</em> use strict; <em>otherwise</em> undef</span></td>
<td>nil</td>
<td><span style="color: gray"><em>raises</em> groovy.lang.MissingPropertyException</span></td>
</tr>
<tr>
<td><a name="conditional-expr" id="conditional-expr"></a><a href="more#conditional-expr-note">conditional expression</a></td>
<td>$x &gt; 0 ? $x : -$x</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>x &gt; 0 ? x : -x</td>
</tr>
<tr>
<th colspan="4"><a name="arithmetic-logic" id="arithmetic-logic"></a><a href="more#arithmetic-logic-note">arithmetic and logic</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="true-false" id="true-false"></a><a href="more#true-false-note">true and false</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>1 ""</td>
<td>true false</td>
<td>true false</td>
</tr>
<tr>
<td><a name="falsehoods" id="falsehoods"></a><a href="more#falsehoods-note">falsehoods</a></td>
<td>undef 0 0.0 "" "0" ()</td>
<td>false nil</td>
<td>false null 0 0.0 "" [] [:]</td>
</tr>
<tr>
<td><a name="logical-op" id="logical-op"></a><a href="more#logical-op-note">logical operators</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td><span style="white-space: pre-wrap;">&amp;&amp; ||</span> !<br />
<span style="color: gray"><em>lower precedence:</em></span><br />
and or xor not</td>
<td>and or not</td>
<td>&amp;&amp; <span style="white-space: pre-wrap;">||</span> !</td>
</tr>
<tr>
<td><a name="relational-expr" id="relational-expr"></a><a href="more#relational-expr-note">relational expressions</a></td>
<td><span style="color: gray"><em>numbers:</em></span> == != &gt; &lt; &gt;= &lt;=<br />
<span style="color: gray"><em>strings:</em></span> eq ne gt lt ge le</td>
<td>x &gt; 3</td>
<td>x &gt; 0</td>
</tr>
<tr>
<td><a name="relational-op" id="relational-op"></a><a href="more#relational-op-note">relational operators</a></td>
<td></td>
<td>== ~= &lt; &gt; &gt;= &lt;=</td>
<td>== != &gt; &lt; &gt;= &lt;=</td>
</tr>
<tr>
<td><a name="min-max" id="min-max"></a><a href="more#min-max-note">min and max</a></td>
<td>use List::Util qw(min max);<br />
<br />
min(1, 2, 3);<br />
max(1, 2, 3);<br />
<br />
@a = (1, 2, 3);<br />
min(@a);<br />
max(@a);</td>
<td>math.min(1, 2, 3)<br />
math.max(1, 2, 3)<br />
<br />
math.min(unpack({1 ,2 ,3}))<br />
math.max(unpack({1, 2, 3}))</td>
<td>[1, 2, 3].min()<br />
[1, 2, 3].max()<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> binary functions:</span><br />
Math.min(1, 2)<br />
Math.max(1, 2)</td>
</tr>
<tr>
<td><a name="three-val-comparison" id="three-val-comparison"></a><a href="more#three-val-comparison-note">three value comparison</a></td>
<td>0 &lt;=&gt; 1<br />
"do" cmp "re"</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="arith-expr" id="arith-expr"></a><a href="more#arith-expr-note">arithmetic expression</a></td>
<td>+ - * / <span style="color: gray"><em>none</em></span> %</td>
<td>1 + 3</td>
<td>1 + 3</td>
</tr>
<tr>
<td><a name="arith-op" id="arith-op"></a><a href="more#arith-op-note">arithmetic operators</a><br />
<span style="color: gray"><em>addition, subtraction, multiplication, float division, quotient, modulus</em></span></td>
<td></td>
<td>+ - * / <span style="color: gray"><em>none</em></span> % ^</td>
<td>+ - * / <span style="color: gray"><em>??</em></span> %</td>
</tr>
<tr>
<td><a name="int-div" id="int-div"></a><a href="more#int-div-note">integer division</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>int(13 / 5)</td>
<td>math.floor(x / y)</td>
<td>Math.floor(x / y)</td>
</tr>
<tr>
<td><a name="int-div-zero" id="int-div-zero"></a><a href="more#int-div-zero-note">integer division by zero</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td><span style="color: gray"><em>error</em></span></td>
<td><span style="color: gray"><em>returns assignable value</em> inf, nan, or -inf <em>depending upon whether dividend is positive, zero, or negative.<br />
<br />
There are no literals for any of these values.</em></span></td>
<td><span style="color: gray"><em>raises</em> java.lang.ArithmeticException</span></td>
</tr>
<tr>
<td><a name="float-div" id="float-div"></a><a href="more#float-div-note">float division</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>13 / 5</td>
<td>x / y</td>
<td>x / y</td>
</tr>
<tr>
<td><a name="float-div-zero" id="float-div-zero"></a><a href="more#float-div-zero-note">float division by zero</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td><span style="color: gray"><em>error</em></span></td>
<td><span style="color: gray"><em>same behavior as for integers</em></span></td>
<td><span style="color: gray"><em>raises</em> java.lang.ArithmeticException</span></td>
</tr>
<tr>
<td><a name="power" id="power"></a><a href="more#power-note">power</a></td>
<td>2 <span style="white-space: pre-wrap;">**</span> 32</td>
<td>2 ^ 32<br />
math.pow(2, 32)</td>
<td>2 ** 32</td>
</tr>
<tr>
<td><a name="sqrt" id="sqrt"></a><a href="more#sqrt-note">sqrt</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>sqrt(2)</td>
<td>math.sqrt(2)</td>
<td>Math.sqrt(2)</td>
</tr>
<tr>
<td><a name="sqrt-negative-one" id="sqrt-negative-one"></a><a href="more#sqrt-negative-one-note">sqrt -1</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td><span style="color: gray"><em>error unless</em> use Math::Complex <em>in effect</em></span></td>
<td>nan</td>
<td>Double.NaN</td>
</tr>
<tr>
<td><a name="transcendental-func" id="transcendental-func"></a><a href="more#transcendental-func-note">transcendental functions</a></td>
<td>use Math::Trig qw(tan asin acos atan);<br />
<br />
exp log sin cos tan asin acos atan atan2</td>
<td>math.exp math.log math.sin math.cos math.tan math.asin math.acos math.atan math.atan2</td>
<td>Math.exp Math.log Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2</td>
</tr>
<tr>
<td><a name="transcendental-const" id="transcendental-const"></a><a href="more#transcendental-const-note">transcendental constants</a><br />
<span style="color: gray"><em>π and e</em></span></td>
<td></td>
<td>math.pi<br />
math.exp(1)</td>
<td>Math.PI<br />
Math.E</td>
</tr>
<tr>
<td><a name="float-truncation" id="float-truncation"></a><a href="more#float-truncation-note">float truncation</a><br />
<span style="color: gray"><em>round towards zero, round to nearest integer, round down, round up</em></span></td>
<td><span style="color: gray"># cpan -i Number::Format</span><br />
use Number::Format 'round';<br />
use POSIX qw(ceil floor);<br />
<br />
int($x)<br />
round($x, 0)<br />
ceil($x)<br />
floor($x)</td>
<td><span style="color: gray"><em>none</em></span><br />
<span style="color: gray"><em>none</em></span><br />
math.floor(3.1)<br />
math.ceil(3.1)</td>
<td>(int)3.1<br />
Math.round(3.1)<br />
(int)Math.floor(3.1)<br />
(int)Math.ceil(3.1)</td>
</tr>
<tr>
<td><a name="absolute-val" id="absolute-val"></a><a href="more#absolute-val-note">absolute value</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>abs($x)</td>
<td>math.abs(-3)</td>
<td>Math.abs(-3)</td>
</tr>
<tr>
<td><a name="int-overflow" id="int-overflow"></a><a href="more#int-overflow-note">integer overflow</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td><span style="color: gray"><em>converted to float;</em> use Math::BigInt <em>to create arbitrary length integers</em></span></td>
<td><span style="color: gray"><em>all numbers are floats</em></span></td>
<td><span style="color: gray"><em>becomes type</em> java.math.BigInteger</span></td>
</tr>
<tr>
<td><a name="float-overflow" id="float-overflow"></a><a href="more#float-overflow-note">float overflow</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>inf</td>
<td>inf</td>
<td>Double.POSITIVE_INFINITY</td>
</tr>
<tr>
<td><a name="rational-construction" id="rational-construction"></a><a href="more#rational-construction-note">rational construction</a></td>
<td>use Math::BigRat;<br />
<br />
my $x = Math::BigRat-&gt;new("22/7");</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="rational-decomposition" id="rational-decomposition"></a><a href="more#rational-decomposition-note">rational decomposition</a></td>
<td>$x-&gt;numerator();<br />
$x-&gt;denominator();</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="complex-construction" id="complex-construction"></a><a href="more#complex-construction-note">complex construction</a></td>
<td>use Math::Complex;<br />
<br />
my $z = 1 + 1.414 * i;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="complex-decomposition" id="complex-decomposition"></a><a href="more#complex-decomposition-note">complex decomposition</a><br />
<span style="color: gray"><em>real and imaginary component, argument, absolute value, conjugate</em></span></td>
<td>Re($z);<br />
Im($z);<br />
arg($z);<br />
abs($z);<br />
~$z;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="random-num" id="random-num"></a><a href="more#random-num-note">random number</a><br />
<span style="color: gray"><em>uniform integer, uniform float, normal float</em></span></td>
<td>int(rand() * 100)<br />
rand()<br />
<span style="color: gray"><em>none</em></span></td>
<td>math.random(100) - 1<br />
math.random()<br />
<span style="color: gray"><em>none</em></span></td>
<td>rnd = new Random()<br />
rnd.nextInt(100)<br />
rnd.nextDouble()</td>
</tr>
<tr>
<td><a name="random-seed" id="random-seed"></a><a href="more#random-seed-note">random seed</a><br />
<span style="color: gray"><em>how to set</em></span></td>
<td>srand 17;<br />
<br />
my $seed = srand;<br />
srand($seed);</td>
<td>math.randomseed(17)</td>
<td>rnd = new Random()<br />
rnd.setSeed(17)</td>
</tr>
<tr>
<td><a name="bit-op" id="bit-op"></a><a href="more#bit-op-note">bit operators</a><br />
<span style="color: gray"><em>left shift, right shift, and, inclusive or, exclusive or, complement</em></span></td>
<td><span style="white-space: pre-wrap;">&lt;&lt; &gt;&gt; &amp; | ^ ~</span></td>
<td><span style="color: gray"><em>none</em></span></td>
<td><span style="white-space: pre-wrap;">&lt;&lt; &gt;&gt; &amp; | ^ ~</span></td>
</tr>
<tr>
<td><a name="binary-oct-hex-literals" id="binary-oct-hex-literals"></a><a href="more#binary-oct-hex-literals-note">binary, octal, and hex literals</a></td>
<td>0b101010<br />
052<br />
0x2a</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="radix" id="radix"></a><a href="more#radix-note">radix</a></td>
<td><span style="color: gray"># cpan -i Math::BaseCalc</span><br />
use Math::BaseCalc;<br />
<br />
$c = new Math::BaseCalc(<br />
<span style="white-space: pre-wrap;">  </span>digits =&gt; [0..6]);<br />
$c-&gt;to_base(42);<br />
$c-&gt;from_base("60");</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="strings" id="strings"></a><a href="more#strings-note">strings</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="str-literal" id="str-literal"></a><a href="more#str-literal-note">string literal</a></td>
<td>"don't say \"no\""<br />
'don\'t say "no"'</td>
<td>"don't say \"no\""<br />
'don\'t say "no"'</td>
<td>"don't say \"no\""<br />
'don\'t say "no"'<br />
"""don't say "no\""""<br />
'''don't say "no"'''<br />
/don't say "no"/</td>
</tr>
<tr>
<td><a name="str-literal-newline" id="str-literal-newline"></a><a href="more#str-literal-newline-note">newline in literal</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>'first line<br />
second line'<br />
<br />
"first line<br />
second line"</td>
<td><span style="color: gray"><em>yes, if preceded by backslash</em></span></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> triple quote literals only:</span><br />
"""foo<br />
bar"""<br />
<br />
'''foo<br />
bar'''</td>
</tr>
<tr>
<td><a name="char-esc" id="char-esc"></a><a href="more#char-esc-note">literal escapes</a></td>
<td><span style="color: gray"><em>double quoted:</em></span><br />
\a \b \cx \e \f \n \r \t \xhh \x{hhhh} \ooo \o{ooo}<br />
<br />
<span style="color: gray"><em>single quoted:</em></span><br />
\' \\</td>
<td><span style="color: gray"><em>single and double quotes:</em></span><br />
\a \b \f \n \r \t \v \" \' \\ \<span style="color: gray"><em>ddd</em></span></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> single and double quotes<br />
<span style="white-space: pre-wrap;">//</span> including triple quotes:</span><br />
\b \f \n \r \t<br />
<span style="white-space: pre-wrap;">\\</span> \" \'<br />
\u<span style="color: gray"><em>hhhh</em></span> \<span style="color: gray"><em>o</em></span> \<span style="color: gray"><em>oo</em></span> \<span style="color: gray"><em>ooo</em></span><br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> slash quotes:</span><br />
\/</td>
</tr>
<tr>
<td><a name="here-doc" id="here-doc"></a><a href="more#here-doc-note">here document</a></td>
<td>$word = "amet";<br />
<br />
$s = «EOF;<br />
lorem ipsum<br />
dolor sit $word<br />
EOF</td>
<td><span style="color: gray"><em>none</em></span></td>
<td><span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="var-interpolation" id="var-interpolation"></a><a href="more#var-interpolation-note">variable interpolation</a></td>
<td>my $count = 3;<br />
my $item = "ball";<br />
print "$count ${item}s\n";</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>count = 3<br />
item = "ball"<br />
<br />
"$count ${item}s"<br />
"""$count ${item}s"""</td>
</tr>
<tr>
<td><a name="expr-interpolation" id="expr-interpolation"></a><a href="more#expr-interpolation-note">expression interpolation</a></td>
<td><span style="color: gray"><em>none</em></span></td>
<td><span style="color: gray"><em>none</em></span></td>
<td>"1 + 1 = ${1 + 1}"<br />
"""1 + 1 = ${1 + 1}"""</td>
</tr>
<tr>
<td><a name="str-concat" id="str-concat"></a><a href="more#str-concat-note">concatenate</a></td>
<td>my $s = "Hello, ";<br />
my $s2 = $s . "World!";</td>
<td>s = "Hello, " .. "World!"</td>
<td>s = "Hello, " + "World!"</td>
</tr>
<tr>
<td><a name="str-replicate" id="str-replicate"></a><a href="more#str-replicate-note">replicate</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>my $hbar = "-" x 80;</td>
<td>string.rep("-", 80)</td>
<td>hbar = "-" * 80</td>
</tr>
<tr>
<td><a name="sprintf" id="sprintf"></a><a href="more#sprintf-note">sprintf</a></td>
<td>my $fmt = "lorem %s %d %f";<br />
sprintf($fmt, "ipsum", 13, 3.7)</td>
<td>string.format("lorem %s %d %.2f", "ipsum", 13, 3.7)</td>
<td>fmt = "lorem %s %d %.2f"<br />
String.format(fmt, "ipsum", 13, 3.7)</td>
</tr>
<tr>
<td><a name="case" id="case"></a><a href="more#case-note">case manipulation</a></td>
<td>uc("lorem")<br />
lc("LOREM")</td>
<td>string.upper("lorem")<br />
string.lower("LOREM")</td>
<td>"lorem".toUpperCase()<br />
"LOREM".toLowerCase()</td>
</tr>
<tr>
<td><a name="capitalize" id="capitalize"></a><a href="more#capitalize-note">capitalize</a><br />
<span style="color: gray"><em>string, words</em></span></td>
<td><span style="color: gray"># cpan -i Text::Autoformat</span><br />
use Text::Autoformat;<br />
<br />
ucfirst("lorem")<br />
autoformat("lorem ipsum",<br />
<span style="white-space: pre-wrap;">  </span>{case =&gt; 'title'})</td>
<td><span style="color: gray"><em>none</em></span><br />
<span style="color: gray"><em>none</em></span></td>
<td>"lorem".capitalize()<br />
<span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="trim" id="trim"></a><a href="more#trim-note">trim</a></td>
<td><span style="color: gray"># cpan -i Text::Trim</span><br />
use Text::Trim;<br />
<br />
trim " lorem "<br />
ltrim " lorem"<br />
rtrim "lorem "</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>" lorem ".trim()</td>
</tr>
<tr>
<td><a name="pad" id="pad"></a><a href="more#pad-note">pad</a><br />
<span style="color: gray"><em>on right, on left, centered</em></span></td>
<td><span style="color: gray"># cpan -i Text::Format</span><br />
use Text::Format;<br />
<br />
sprintf("%-10s", "lorem")<br />
sprintf("%10s", "lorem")<br />
<br />
$text = Text::Format-&gt;new(columns =&gt; 10);<br />
$text-&gt;center("lorem");</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>"lorem".padRight(10)<br />
"lorem".padLeft(10)<br />
"lorem.center(10)</td>
</tr>
<tr>
<td><a name="str-to-num" id="str-to-num"></a><a href="more#str-to-num-note">string to number</a></td>
<td>7 + "12"<br />
73.9 + ".037"</td>
<td>7 + tonumber("12")<br />
73.9 + tonumber(".037")<br />
<span style="color: gray"><em>arithmetic operators attempt numeric conversion of string operands</em></span></td>
<td>7 + Integer.parseInt("12")<br />
73.9 + Double.parseDouble(".037")</td>
</tr>
<tr>
<td><a name="num-to-str" id="num-to-str"></a><a href="more#num-to-str-note">number to string</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>"value: " . 8</td>
<td>"value: " .. 8</td>
<td>"value: " + 8<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> explicit conversion:</span><br />
8.toString()</td>
</tr>
<tr>
<td><a name="join" id="join"></a><a href="more#join-note">join</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>join(" ", qw(do re mi fa))</td>
<td>table.concat({"do", "re", "mi"}, " ")</td>
<td>["do", "re", "mi"].join(" ")</td>
</tr>
<tr>
<td><a name="split" id="split"></a><a href="more#split-note">split</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>split(/\s+/, "do re mi fa")</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>"do re mi".split()</td>
</tr>
<tr>
<td><a name="split-in-two" id="split-in-two"></a><a href="more#split-in-two-note">split in two</a></td>
<td>split(/\s+/, "do re mi fa", 2)</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="split-keep-delimiters" id="split-keep-delimiters"></a><a href="more#split-keep-delimiters-note">split and keep delimiters</a></td>
<td>split(/(\s+)/, "do re mi fa")</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="str-length" id="str-length"></a><a href="more#str-length-note">length</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>length("lorem")</td>
<td>string.len("lorem")</td>
<td>"lorem".size()<br />
"lorem".length()</td>
</tr>
<tr>
<td><a name="index-substr" id="index-substr"></a><a href="more#index-substr-note">index of substring</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td><span style="color: gray"># returns -1 if not found:</span><br />
index("lorem ipsum", "ipsum")<br />
rindex("do re re", "re")</td>
<td>string.find("lorem ipsum", "ipsum")</td>
<td>"lorem ipsum".indexOf("ipsum")</td>
</tr>
<tr>
<td><a name="extract-substr" id="extract-substr"></a><a href="more#extract-substr-note">extract substring</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>substr("lorem ipsum", 6, 5)</td>
<td>string.sub("lorem ipsum", 7, 11)</td>
<td>"lorem ipsum".substring(6, 11)</td>
</tr>
<tr>
<td><a name="lookup-char" id="lookup-char"></a><a href="more#lookup-char-note">character lookup</a></td>
<td><span style="color: gray"># can't use index notation with<br />
# strings:</span><br />
substr("lorem ipsum", 6, 1)</td>
<td></td>
<td>"lorem ipsum"[6]</td>
</tr>
<tr>
<td><a name="chr-ord" id="chr-ord"></a><a href="more#chr-ord-note">chr and ord</a></td>
<td>chr(65)<br />
ord("A")</td>
<td>string.char(65)<br />
string.byte("A")</td>
<td>(Character)65<br />
(Integer)'A'</td>
</tr>
<tr>
<td><a name="str-to-char-array" id="str-to-char-array"></a><a href="more#str-to-char-array-note">to array of characters</a></td>
<td>split(<span style="white-space: pre-wrap;">//</span>, "abcd")</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="translate-char" id="translate-char"></a><a href="more#translate-char-note">translate characters</a></td>
<td>$s = "hello";<br />
$s =~ tr/a-z/n-za-m/;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="delete-char" id="delete-char"></a><a href="more#delete-char-note">delete characters</a></td>
<td>$s = "disemvowel me";<br />
$s =~ tr/aeiou<span style="white-space: pre-wrap;">//</span>d;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="squeeze-char" id="squeeze-char"></a><a href="more#squeeze-char-note">squeeze characters</a></td>
<td>$s = "too much space";<br />
$s =~ tr/ <span style="white-space: pre-wrap;">//</span>s;</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="regexes" id="regexes"></a><a href="more#regexes-note">regular expressions</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="regex-literal" id="regex-literal"></a><a href="more#regex-literal-note">literal, custom delimited literal</a></td>
<td>/lorem|ipsum/<br />
qr(/etc/hosts)</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="char-class-abbrev" id="char-class-abbrev"></a><a href="more#char-class-abbrev-note">character class abbreviations and anchors</a></td>
<td>. \d \D \h \H \s \S \v \V \w \W</td>
<td><span style="color: gray"><em>char class abbrevs:</em></span><br />
. %a %c %d %l %p %s %u %w %x %z<br />
<br />
<span style="color: gray"><em>anchors:</em></span> ^ $</td>
<td><span style="color: gray"><em>char class abbrevs:</em></span><br />
. \d \D \s \S \w \W<br />
<br />
<span style="color: gray"><em>anchors:</em></span> ^ $ \b</td>
</tr>
<tr>
<td><a name="regex-anchors" id="regex-anchors"></a><a href="more#regex-anchors-note">anchors</a></td>
<td>^ $ \A \b \B \z \Z</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="regex-match" id="regex-match"></a><a href="more#regex-match-note">match test</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>if ($s =~ /1999/) {<br />
<span style="white-space: pre-wrap;">  </span>print "party!\n";<br />
}</td>
<td>if string.match(s, "1999") then<br />
<span style="white-space: pre-wrap;">  </span>print("party!")<br />
end</td>
<td>s = "it is 1999"<br />
<br />
if (s =~ /1999/) {<br />
<span style="white-space: pre-wrap;">  </span>println("party!")<br />
}</td>
</tr>
<tr>
<td><a name="case-insensitive-regex" id="case-insensitive-regex"></a><a href="more#case-insensitive-regex-note">case insensitive match test</a></td>
<td>"Lorem" =~ /lorem/i</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>"Lorem" =~ /(?i)lorem/</td>
</tr>
<tr>
<td><a name="regex-modifiers" id="regex-modifiers"></a><a href="more#regex-modifiers-note">modifiers</a></td>
<td>i m s p x</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>i s</td>
</tr>
<tr>
<td><a name="subst" id="subst"></a><a href="more#subst-note">substitution</a></td>
<td>my $s = "do re mi mi mi";<br />
$s =~ s/mi/ma/g;</td>
<td>s = "do re mi mi mi"<br />
s = string.gsub(s, "mi", "ma")</td>
<td>"do re mi mi mi".replaceAll(/mi/, "ma")</td>
</tr>
<tr>
<td><a name="match-prematch-postmatch" id="match-prematch-postmatch"></a><a href="more#match-prematch-postmatch-note">match, prematch, postmatch</a></td>
<td>f ($s =~ /\d{4}/p) {<br />
<span style="white-space: pre-wrap;">  </span>$match = ${^MATCH};<br />
<span style="white-space: pre-wrap;">  </span>$prematch = ${^PREMATCH};<br />
<span style="white-space: pre-wrap;">  </span>$postmatch = ${^POSTMATCH};<br />
}</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="group-capture" id="group-capture"></a><a href="more#group-capture-note">group capture</a></td>
<td>$rx = qr/(\d{4})-(\d{2})-(\d{2})/;<br />
"2010-06-03" =~ $rx;<br />
($yr, $mo, $dy) = ($1, $2, $3);</td>
<td>s = "2010-06-03"<br />
rx = "(%d+)-(%d+)-(%d+)"<br />
yr, mo, dy = string.match(s, rx)</td>
<td>s = "2010-06-03"<br />
m = s =~ /(\d{4})-(\d{2})-(\d{2})/<br />
yr = m.group(1)<br />
mo = m.group(2)<br />
dy = m.group(3)</td>
</tr>
<tr>
<td><a name="named-group-capture" id="named-group-capture"></a><a href="more#named-group-capture-note">named group capture</a></td>
<td>$s = "foo.txt";<br />
$s =~ /^(?&lt;file&gt;.+)\.(?&lt;suffix&gt;.+)$/;<br />
<br />
$+{"file"}<br />
$+{"suffix"}</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="scan" id="scan"></a><a href="more#scan-note">scan</a></td>
<td>my $s = "dolor sit amet";<br />
@a = $s =~ m/\w+/g;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="backreference" id="backreference"></a><a href="more#backreference-note">backreference</a><br />
<span style="color: gray"><em>in regex, in substitution string</em></span></td>
<td>"do do" =~ /(\w+) \1/<br />
<br />
my $s = "do re";<br />
$s =~ s/(\w+) (\w+)/$2 $1/;</td>
<td>string.match("do do", "(%w+) %1")<br />
<br />
rx = "(%w+) (%w+)"<br />
string.gsub("do re", rx, "%2 %1")</td>
<td>"do do" =~ /(\w+) \1/<br />
<br />
rx = /(\w+) (\w+)/<br />
"do re".replaceAll(rx, '$2 $1')</td>
</tr>
<tr>
<td><a name="recursive-regex" id="recursive-regex"></a><a href="more#recursive-regex-note">recursive regex</a></td>
<td>/\(([^()]*|(?R))\)/</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="dates-time" id="dates-time"></a><a href="more#dates-time-note">dates and time</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="date-time-type" id="date-time-type"></a><a href="more#date-time-type-note">date/time type</a></td>
<td><span style="color: gray">Time::Piece <em>if</em> use Time::Piece <em>in effect, otherwise tm array</em></span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="current-date-time" id="current-date-time"></a><a href="more#current-date-time-note">current date/time</a></td>
<td>use Time::Piece;<br />
<br />
my $t = localtime(time);<br />
my $utc = gmtime(time);</td>
<td>t = os.time()</td>
<td>t = new Date()</td>
</tr>
<tr>
<td><a name="unix-epoch" id="unix-epoch"></a><a href="more#unix-epoch-note">to unix epoch, from unix epoch</a></td>
<td>use Time::Local;<br />
use Time::Piece;<br />
<br />
my $epoch = timelocal($t);<br />
my $t2 = localtime(1304442000);</td>
<td>t<br />
t2 = 1315716177</td>
<td>Math.round(t.getTime() / 1000)<br />
t = new Date(1315716177 * 1000)</td>
</tr>
<tr>
<td><a name="current-unix-epoch" id="current-unix-epoch"></a><a href="more#current-unix-epoch-note">current unix epoch</a></td>
<td>$epoch = time;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="strftime" id="strftime"></a><a href="more#strftime-note">strftime</a></td>
<td>use Time::Piece;<br />
<br />
$t = localtime(time);<br />
$fmt = "%Y-%m-%d %H:%M:%S";<br />
print $t-&gt;strftime($fmt);</td>
<td>os.date("%Y-%m-%d %H:%M:%S", t)</td>
<td></td>
</tr>
<tr>
<td><a name="strptime" id="strptime"></a><a href="more#strptime-note">strptime</a></td>
<td>use Time::Local;<br />
use Time::Piece;<br />
<br />
$s = "2011-05-03 10:00:00";<br />
$fmt = "%Y-%m-%d %H:%M:%S";<br />
$t = Time::Piece-&gt;strptime($s,$fmt);</td>
<td><span style="color: gray"><em>none</em></span></td>
<td></td>
</tr>
<tr>
<td><a name="parse-date" id="parse-date"></a><a href="more#parse-date-note">parse date w/o format</a></td>
<td><span style="color: gray"># cpan -i Date::Parse</span><br />
use Date::Parse;<br />
<br />
$epoch = str2time("July 7, 1999");</td>
<td><span style="color: gray"><em>none</em></span></td>
<td></td>
</tr>
<tr>
<td><a name="get-date-parts" id="get-date-parts"></a><a href="more#get-date-parts-note">get date parts</a></td>
<td>$t-&gt;year<br />
$t-&gt;mon<br />
$t-&gt;mday</td>
<td><span style="color: gray"><em>none</em></span></td>
<td></td>
</tr>
<tr>
<td><a name="get-time-parts" id="get-time-parts"></a><a href="more#get-time-parts-note">get time parts</a></td>
<td>$t-&gt;hour<br />
$t-&gt;min<br />
$t-&gt;sec</td>
<td><span style="color: gray"><em>none</em></span></td>
<td></td>
</tr>
<tr>
<td><a name="date-from-parts" id="date-from-parts"></a><a href="more#date-from-parts-note">build date/time from parts</a></td>
<td>$dt = DateTime-&gt;new(<br />
<span style="white-space: pre-wrap;">  </span>year=&gt;2014,<br />
<span style="white-space: pre-wrap;">  </span>month=&gt;4,<br />
<span style="white-space: pre-wrap;">  </span>day=&gt;1,<br />
<span style="white-space: pre-wrap;">  </span>hour=&gt;10,<br />
<span style="white-space: pre-wrap;">  </span>minute=&gt;3,<br />
<span style="white-space: pre-wrap;">  </span>second=&gt;56);</td>
<td><span style="color: gray"><em>none</em></span></td>
<td></td>
</tr>
<tr>
<td><a name="date-subtraction" id="date-subtraction"></a><a href="more#date-subtraction-note">result of date subtraction</a></td>
<td><span style="color: gray">Time::Seconds <em>object if</em> use Time::Piece <em>in effect; not meaningful to subtract tm arrays</em></span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="add-time-duration" id="add-time-duration"></a><a href="more#add-time-duration-note">add time duration</a></td>
<td>use Time::Seconds;<br />
<br />
$now = localtime(time);<br />
$now += 10 * ONE_MINUTE() + 3;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="local-tmz" id="local-tmz"></a><a href="more#local-tmz-note">local timezone</a></td>
<td><span style="color: gray">Time::Piece <em>has local timezone if created with localtime and UTC timezone if created with gmtime; tm arrays have no timezone or offset info</em></span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="tmz-offset" id="tmz-offset"></a><a href="more#tmz-offset-note">timezone name; offset from UTC; is daylight savings?</a></td>
<td><span style="color: gray"># cpan -i DateTime</span><br />
use DateTime;<br />
use DateTime::TimeZone;<br />
<br />
$dt = DateTime-&gt;now();<br />
$tz = DateTime::TimeZone-&gt;new(<br />
<span style="white-space: pre-wrap;">  </span>name=&gt;"local");<br />
<br />
$tz-&gt;name;<br />
$tz-&gt;offset_for_datetime($dt) /<br />
<span style="white-space: pre-wrap;">  </span>3600;<br />
$tz-&gt;is_dst_for_datetime($dt);</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="microseconds" id="microseconds"></a><a href="more#microseconds-note">microseconds</a></td>
<td>use Time::HiRes qw(gettimeofday);<br />
<br />
($sec, $usec) = gettimeofday;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="sleep" id="sleep"></a><a href="more#sleep-note">sleep</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td><span style="color: gray"># a float argument will be truncated<br />
# to an integer:</span><br />
sleep 1;</td>
<td><span style="color: gray"><em>none</em></span></td>
<td></td>
</tr>
<tr>
<td><a name="timeout" id="timeout"></a><a href="more#timeout-note">timeout</a></td>
<td>eval {<br />
<span style="white-space: pre-wrap;">  </span>$SIG{ALRM}= sub {die "timeout!";};<br />
<span style="white-space: pre-wrap;">  </span>alarm 5;<br />
<span style="white-space: pre-wrap;">  </span>sleep 10;<br />
};<br />
alarm 0;</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="arrays" id="arrays"></a><a href="more#arrays-note">arrays</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="array-literal" id="array-literal"></a><a href="more#array-literal-note">literal</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>@a = (1, 2, 3, 4);</td>
<td>a = { 1, 2, 3, 4 }</td>
<td>a = [1, 2, 3, 4]</td>
</tr>
<tr>
<td><a name="quote-words" id="quote-words"></a><a href="more#quote-words-note">quote words</a></td>
<td>@a = qw(do re mi);</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="array-size" id="array-size"></a><a href="more#array-size-note">size</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>$#a + 1<br />
scalar(@a)</td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">--</span> not well-defined if array<br />
<span style="white-space: pre-wrap;">--</span> contains nil values:</span><br />
# a</td>
<td>a.size</td>
</tr>
<tr>
<td><a name="array-lookup" id="array-lookup"></a><a href="more#array-lookup-note">lookup</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>$a[0]<br />
<br />
<span style="color: gray"># returns last element:</span><br />
$a[-1]</td>
<td>a[1]</td>
<td>a[0]</td>
</tr>
<tr>
<td><a name="array-update" id="array-update"></a><a href="more#array-update-note">update</a></td>
<td>$a[0] = "lorem";</td>
<td>a[1] = "lorem"</td>
<td>a[0] = 'lorem'</td>
</tr>
<tr>
<td><a name="array-out-of-bounds" id="array-out-of-bounds"></a><a href="more#array-out-of-bounds-note">out-of-bounds behavior</a></td>
<td>@a = ();<br />
<span style="color: gray"># evaluates as undef:</span><br />
$a[10];<br />
<span style="color: gray"># increases array size to 11:</span><br />
$a[10] = "lorem";</td>
<td><span style="color: gray"><em>returns</em> nil</span></td>
<td><span style="color: gray"><em>returns</em> null</span></td>
</tr>
<tr>
<td><a name="array-element-index" id="array-element-index"></a><a href="more#array-element-index-note">index of element</a><br />
<span style="color: gray"><em>first and last occurrence</em></span></td>
<td>use List::Util 'first';<br />
<br />
@a = qw(x y z w);<br />
$i = first {$a[$_] eq "y"} (0..$#a);</td>
<td><span style="color: gray"><em>none; use</em> for <em>and</em> ipairs</span></td>
<td>[6, 7, 7, 8].indexOf(7)<br />
[6, 7, 7, 8].lastIndexOf(7)<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> returns -1 if not found</span></td>
</tr>
<tr>
<td><a name="array-slice" id="array-slice"></a><a href="more#array-slice-note">slice</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td><span style="color: gray"># select 3rd and 4th elements:</span><br />
@a[2..3]<br />
splice(@a, 2, 2)</td>
<td><span style="color: gray"><em>none</em></span></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> ['b', 'c']:</span><br />
['a', 'b', 'c', 'd'][1..2]</td>
</tr>
<tr>
<td><a name="array-slice-to-end" id="array-slice-to-end"></a><a href="more#array-slice-to-end-note">slice to end</a></td>
<td>@a[1..$#a]</td>
<td><span style="color: gray"><em>none</em></span></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> ['b', 'c', 'd']:</span><br />
['a', 'b', 'c', 'd'][1..-1]</td>
</tr>
<tr>
<td><a name="array-back" id="array-back"></a><a href="more#array-back-note">manipulate back</a></td>
<td>@a = (6, 7, 8);<br />
push @a, 9;<br />
pop @a;</td>
<td>a = {6, 7, 8}<br />
table.insert(a, 9)<br />
i = table.remove(a)</td>
<td>a = [6, 7, 8]<br />
a.push(9)<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> also:</span><br />
a <span style="white-space: pre-wrap;">&lt;&lt;</span> 9<br />
i = a.pop()</td>
</tr>
<tr>
<td><a name="array-front" id="array-front"></a><a href="more#array-front-note">manipulate front</a></td>
<td>@a = (6, 7, 8);<br />
unshift @a, 5;<br />
shift @a;</td>
<td>a = {6, 7, 8}<br />
table.insert(a, 1, 5)<br />
i = table.remove(a, 1)</td>
<td>a = [6, 7, 8]<br />
a.add(0, 5)<br />
i = a.remove(0)</td>
</tr>
<tr>
<td><a name="array-concat" id="array-concat"></a><a href="more#array-concat-note">concatenate</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>@a = (1, 2, 3);<br />
@a2 = (@a, (4, 5, 6));<br />
push @a, (4,5,6);</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>[1, 2, 3] + [4, 5, 6]</td>
</tr>
<tr>
<td><a name="array-replicate" id="array-replicate"></a><a href="more#array-replicate-note">replicate</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>@a = (undef) x 10;</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>a = [null] * 10</td>
</tr>
<tr>
<td><a name="array-copy" id="array-copy"></a><a href="more#array-copy-note">copy</a><br />
<span style="color: gray"><em>address copy, shallow copy, deep copy</em></span></td>
<td>use Storable 'dclone'<br />
<br />
my @a = (1,2,[3,4]);<br />
my $a2 = \@a;<br />
my @a3 = @a;<br />
my @a4 = @{dclone(\@a)};</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="array-arg" id="array-arg"></a><a href="more#array-arg-note">arrays as function arguments</a></td>
<td><span style="color: gray"><em>each element passed as separate argument; use reference to pass array as single argument</em></span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="array-iter" id="array-iter"></a><a href="more#array-iter-note">iterate over elements</a></td>
<td>for $i (1, 2, 3) { print "$i\n" }</td>
<td>for k,v in ipairs(a) do<br />
<span style="white-space: pre-wrap;">  </span>print(v)<br />
end</td>
<td>for (i in [1, 2, 3, 4]) {<br />
<span style="white-space: pre-wrap;">  </span>println i<br />
}</td>
</tr>
<tr>
<td><a name="range-iteration" id="range-iteration"></a><a href="more#range-iteration-note">iterate over range</a></td>
<td>for $i (1..1_000_000) {<br />
<span style="white-space: pre-wrap;">  </span><span style="color: gray"><em>code</em></span><br />
}</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="range-array" id="range-array"></a><a href="more#range-array-note">instantiate range as array</a></td>
<td>@a = 1..10;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="array-reverse" id="array-reverse"></a><a href="more#array-reverse-note">reverse</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>@a = (1, 2, 3);<br />
<br />
reverse @a;<br />
@a = reverse @a;</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>a = [1, 2, 3]<br />
a.reverse()</td>
</tr>
<tr>
<td><a name="array-sort" id="array-sort"></a><a href="more#array-sort-note">sort</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>@a = qw(b A a B);<br />
<br />
sort @a;<br />
@a = sort @a;<br />
sort { lc($a) cmp lc($b) } @a;</td>
<td>a = {3, 1, 4, 2}<br />
table.sort(a)</td>
<td>a = [3, 1, 4, 2]<br />
a.sort()</td>
</tr>
<tr>
<td><a name="array-dedupe" id="array-dedupe"></a><a href="more#array-dedupe-note">dedupe</a></td>
<td>use List::MoreUtils 'uniq';<br />
<br />
my @a = (1, 2, 2, 3);<br />
<br />
my @a2 = uniq @a;<br />
@a = uniq @a;</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>a = [1, 2, 2, 3]<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> modifies array in place:</span><br />
a.unique()</td>
</tr>
<tr>
<td><a name="membership" id="membership"></a><a href="more#membership-note">membership</a></td>
<td>7 ~~ @a</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>[1, 2, 3].contains(7)<br />
![1, 2, 3].contains(7)</td>
</tr>
<tr>
<td><a name="intersection" id="intersection"></a><a href="more#intersection-note">intersection</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td></td>
<td><span style="color: gray"><em>none</em></span></td>
<td>[1, 2].intersect([2, 3])</td>
</tr>
<tr>
<td><a name="union" id="union"></a><a href="more#union-note">union</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td></td>
<td><span style="color: gray"><em>none</em></span></td>
<td>([1, 2] + [2, 3, 4]).unique()</td>
</tr>
<tr>
<td><a name="set-diff" id="set-diff"></a><a href="more#set-diff-note">relative complement</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td></td>
<td><span style="color: gray"><em>none</em></span></td>
<td>[1 2 3] - [2]</td>
</tr>
<tr>
<td><a name="map" id="map"></a><a href="more#map-note">map</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>map { $_ * $_ } (1,2,3)</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>[1, 2, 3].collect() { n -&gt; n * n }</td>
</tr>
<tr>
<td><a name="filter" id="filter"></a><a href="more#filter-note">filter</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>grep { $_ &gt; 1 } (1,2,3)</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>[1, 2, 3].findAll() { x -&gt; x &gt; 2 }</td>
</tr>
<tr>
<td><a name="reduce" id="reduce"></a><a href="more#reduce-note">reduce</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>use List::Util 'reduce';<br />
<br />
reduce { $x + $y } 0, (1,2,3)</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>[1, 2, 3].inject(0) { x, y -&gt; x + y }</td>
</tr>
<tr>
<td><a name="universal-existential-test" id="universal-existential-test"></a><a href="more#universal-existential-test-note">universal and existential tests</a></td>
<td><span style="color: gray"># cpan -i List::MoreUtils</span><br />
use List::MoreUtils qw(all any);<br />
<br />
all { $_ % 2 == 0 } (1, 2, 3, 4)<br />
any { $_ % 2 == 0 } (1, 2, 3, 4)</td>
<td><span style="color: gray"><em>none</em></span></td>
<td><span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="shuffle" id="shuffle"></a><a href="more#shuffle-note">shuffle</a></td>
<td>use List::Util 'shuffle';<br />
<br />
@a = (1, 2, 3, 4);<br />
shuffle(@a);</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>a = [1, 2, 3, 4]<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> no return value:</span><br />
Collections.shuffle(a)</td>
</tr>
<tr>
<td><a name="zip" id="zip"></a><a href="more#zip-note">zip</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td><span style="color: gray"># cpan -i List::MoreUtils</span><br />
use List::MoreUtils 'zip';<br />
<br />
@nums = (1, 2, 3);<br />
@lets = qw(a b c);<br />
<span style="color: gray"># flat array of 6 elements:</span><br />
@a = zip @nums, @lets;</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>[[1,2,3], ['a', 'b', 'c']].transpose()</td>
</tr>
<tr>
<th colspan="4"><a name="dictionaries" id="dictionaries"></a><a href="more#dictionaries-note">dictionaries</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="dict-literal" id="dict-literal"></a><a href="more#dict-literal-note">literal</a></td>
<td>%d = ( "t" =&gt; 1, "f" =&gt; 0 );<br />
<br />
<span style="color: gray"># barewords permitted in front of =&gt;<br />
# under 'use strict'</span></td>
<td>d = { t=1, f=0 }</td>
<td>d = ["t": 1, "f": 0]</td>
</tr>
<tr>
<td><a name="dict-size" id="dict-size"></a><a href="more#dict-size-note">size</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>scalar(keys %d)</td>
<td>size = 0<br />
for k, v in pairs(d) do<br />
<span style="white-space: pre-wrap;">  </span>size = size + 1<br />
end</td>
<td>d.size()</td>
</tr>
<tr>
<td><a name="dict-lookup" id="dict-lookup"></a><a href="more#dict-lookup-note">lookup</a></td>
<td>$d{"t"}<br />
<br />
<span style="color: gray"># barewords permitted inside { }<br />
# under 'use strict'</span></td>
<td>d.t<br />
d["t"]</td>
<td>d["t"]</td>
</tr>
<tr>
<td><a name="dict-update" id="dict-update"></a><a href="more#dict-update-note">update</a></td>
<td></td>
<td>d["t"] = 2<br />
d.t = 2</td>
<td>d["t"] = 2</td>
</tr>
<tr>
<td><a name="dict-out-of-bounds" id="dict-out-of-bounds"></a><a href="more#dict-out-of-bounds-note">out of bounds behavior</a></td>
<td>%d = ();<br />
<span style="color: gray"># evaluates as undef:</span><br />
$d{"lorem"};<br />
<span style="color: gray"># adds key/value pair:</span><br />
$d{"lorem"} = "ipsum";</td>
<td><span style="color: gray"><em>returns</em></span> nil</td>
<td><span style="color: gray"><em>returns</em> null</span></td>
</tr>
<tr>
<td><a name="dict-key-check" id="dict-key-check"></a><a href="more#dict-key-check-note">is key present</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>exists $d{"y"}</td>
<td>d["t"] ~= nil</td>
<td>d.containsKey("t")</td>
</tr>
<tr>
<td><a name="dict-delete" id="dict-delete"></a><a href="more#dict-delete-note">delete</a></td>
<td>%d = ( 1 =&gt; "t", 0 =&gt; "f" );<br />
delete $d{1};</td>
<td>d.t = nil<br />
d["t"] = nil</td>
<td></td>
</tr>
<tr>
<td><a name="dict-assoc-array" id="dict-assoc-array"></a><a href="more#dict-assoc-array-note">from array of pairs, from even length array</a></td>
<td>@a = (1,"a",2,"b",3,"c");<br />
%d = @a;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="dict-merge" id="dict-merge"></a><a href="more#dict-merge-note">merge</a></td>
<td>%d1 = (a =&gt; 1, b =&gt; 2);<br />
%d2 = (b =&gt; 3, c =&gt; 4);<br />
%d1 = (%d1, %d2);</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="dict-invert" id="dict-invert"></a><a href="more#dict-invert-note">invert</a></td>
<td>%to_num = (t=&gt;1, f=&gt;0);<br />
%to_let = reverse %to_num;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="dict-iter" id="dict-iter"></a><a href="more#dict-iter-note">iteration</a></td>
<td>while (($k, $v) = each %d) {<br />
<span style="white-space: pre-wrap;">  </span><span style="color: gray"><em>code</em></span><br />
}</td>
<td>for k,v in pairs(d) do<br />
<span style="white-space: pre-wrap;">  </span><span style="color: gray"><em>use k or v</em></span><br />
end</td>
<td></td>
</tr>
<tr>
<td><a name="dict-key-val-array" id="dict-key-val-array"></a><a href="more#dict-key-val-array-note">keys and values as arrays</a></td>
<td>keys %d<br />
values %d</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="dict-sort-val" id="dict-sort-val"></a><a href="more#dict-sort-val-note">sort by values</a></td>
<td>foreach $k (sort<br />
<span style="white-space: pre-wrap;">  </span>{ $d{$a} &lt;=&gt; $d{$b} } keys %d) {<br />
<span style="white-space: pre-wrap;">  </span>print "$k: $d{$k}\n";<br />
}</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="dict-default-val" id="dict-default-val"></a><a href="more#dict-default-val-note">default value, computed value</a></td>
<td>my %counts;<br />
$counts{'foo'} += 1<br />
<br />
<span style="color: gray"><em>define a tied hash for computed values and defaults other than zero or empty string</em></span></td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="functions" id="functions"></a><a href="more#functions-note">functions</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="func-def" id="func-def"></a><a href="more#func-def-note">define function</a></td>
<td>sub add3 { $_[0] + $_[1] + $_[2] }<br />
<br />
sub add3 {<br />
<span style="white-space: pre-wrap;">  </span>my ($x1, $x2, $x3) = @_;<br />
<span style="white-space: pre-wrap;">  </span>$x1 + $x2 + $x3;<br />
}</td>
<td>function add(x, y)<br />
<span style="white-space: pre-wrap;">  </span>return x + y<br />
end</td>
<td>def (x, y) {<br />
<span style="white-space: pre-wrap;">  </span>x + y<br />
}</td>
</tr>
<tr>
<td><a name="func-invocation" id="func-invocation"></a><a href="more#func-invocation-note">invoke function</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>add3(1, 2, 3);<br />
<br />
<span style="color: gray"># parens are optional:</span><br />
add3 1, 2, 3;</td>
<td>add(1, 2)</td>
<td>add(1, 2)<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> parens are optional:</span><br />
add 1, 2</td>
</tr>
<tr>
<td><a name="nested-func" id="nested-func"></a><a href="more#nested-func-note">nested function</a></td>
<td><span style="color: gray"><em>defined when containing function is defined; visible outside containing function</em></span></td>
<td><span style="color: gray"><em>visible outside containing function</em></span></td>
<td></td>
</tr>
<tr>
<td><a name="missing-arg" id="missing-arg"></a><a href="more#missing-arg-note">missing argument behavior</a></td>
<td><span style="color: gray"><em>set to</em> undef</span></td>
<td>nil</td>
<td><span style="color: gray"><em>raises</em> groovy.lang.MissingMethodException</span></td>
</tr>
<tr>
<td><a name="extra-arg" id="extra-arg"></a><a href="more#extra-arg-note">extra argument behavior</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td></td>
<td><span style="color: gray"><em>ignored</em></span></td>
<td><span style="color: gray"><em>raises</em> groovy.lang.MissingMethodException</span></td>
</tr>
<tr>
<td><a name="default-arg" id="default-arg"></a><a href="more#default-arg-note">default argument</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>sub my_log {<br />
<span style="white-space: pre-wrap;">  </span>my $x = shift;<br />
<span style="white-space: pre-wrap;">  </span>my $base = shift // 10;<br />
<br />
<span style="white-space: pre-wrap;">  </span>log($x) / log($base);<br />
}<br />
<br />
my_log(42);<br />
my_log(42, exp(1));</td>
<td><span style="color: gray"><em>none</em></span></td>
<td></td>
</tr>
<tr>
<td><a name="var-arg" id="var-arg"></a><a href="more#var-arg-note">collect arguments in array</a></td>
<td>sub first_and_last {<br />
<br />
<span style="white-space: pre-wrap;">  </span>if ( @_ &gt;= 1 ) {<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>print "first: $_[0]\n";<br />
<span style="white-space: pre-wrap;">  </span>}<br />
<br />
<span style="white-space: pre-wrap;">  </span>if ( @_ &gt;= 2 ) {<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>print "last: $_[-1]\n";<br />
<span style="white-space: pre-wrap;">  </span>}<br />
}</td>
<td><span style="color: gray"><em>declare function with ellipsis:</em></span><br />
function foo(<span style="white-space: pre-wrap;">...</span>)<br />
<span style="white-space: pre-wrap;">  </span>local arg = {<span style="white-space: pre-wrap;">...</span>}</td>
<td></td>
</tr>
<tr>
<td><a name="apply-func" id="apply-func"></a><a href="more#apply-func-note">pass array elements as separate arguments</a></td>
<td>@a = (2, 3);<br />
<br />
add3(1, @a);<br />
<br />
<span style="color: gray"># arrays are always expanded when used<br />
# as arguments</span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="retval" id="retval"></a><a href="more#retval-note">return value</a></td>
<td><span style="color: gray">return <em>arg or last expression evaluated</em></span></td>
<td>return <span style="color: gray"><em>arg or</em></span> nil</td>
<td><span style="color: gray">return <em>arg or last expression evaluated</em></span></td>
</tr>
<tr>
<td><a name="multiple-retval" id="multiple-retval"></a><a href="more#multiple-retval-note">multiple return values</a></td>
<td>sub first_and_second {<br />
<span style="white-space: pre-wrap;">  </span>return ($_[0], $_[1]);<br />
}<br />
<br />
@a = (1,2,3);<br />
($x, $y) = first_and_second(@a);</td>
<td>function roots(x)<br />
<span style="white-space: pre-wrap;">  </span>r = math.sqrt(x)<br />
<span style="white-space: pre-wrap;">  </span>return r, -r<br />
end<br />
r1,r2 = roots(4)</td>
<td><span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="lambda-decl" id="lambda-decl"></a><a href="more#lambda-decl-note">anonymous function literal</a></td>
<td>$sqr = sub { $_[0] * $_[0] }</td>
<td>sqr = function(x) return x*x end</td>
<td>sqr = { x -&gt; Math.sqrt x }</td>
</tr>
<tr>
<td><a name="lambda-invocation" id="lambda-invocation"></a><a href="more#lambda-invocation-note">invoke anonymous function</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>$sqr-&gt;(2)</td>
<td>sqr(2)</td>
<td>sqr(2)</td>
</tr>
<tr>
<td><a name="func-as-val" id="func-as-val"></a><a href="more#func-as-val-note">function as value</a></td>
<td>my $func = \&amp;add;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="private-state-func" id="private-state-func"></a><a href="more#private-state-func-note">function with private state</a></td>
<td>use feature state;<br />
<br />
sub counter {<br />
<span style="white-space: pre-wrap;">  </span>state $i = 0;<br />
<span style="white-space: pre-wrap;">  </span>++$i;<br />
}<br />
<br />
print counter() . "\n";</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="closure" id="closure"></a><a href="more#closure-note">closure</a></td>
<td>sub make_counter {<br />
<span style="white-space: pre-wrap;">  </span>my $i = 0;<br />
<span style="white-space: pre-wrap;">  </span>return sub { ++$i };<br />
}<br />
<br />
my $nays = make_counter;<br />
print $nays-&gt;() . "\n";</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="generator" id="generator"></a><a href="more#generator-note">generator</a></td>
<td></td>
<td>crt = coroutine.create(<br />
<span style="white-space: pre-wrap;">  </span>function (n)<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>while (true) do<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>coroutine.yield(n % 2)<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>n = n + 1<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>end<br />
<span style="white-space: pre-wrap;">  </span>end<br />
)<br />
<br />
status, retval =<br />
<span style="white-space: pre-wrap;">  </span>coroutine.resume(crt, 1)<br />
<br />
if status then<br />
<span style="white-space: pre-wrap;">  </span>print("parity: " .. retval)<br />
else<br />
<span style="white-space: pre-wrap;">  </span>print("couldn't resume crt")<br />
end<br />
<br />
_, retval = coroutine.resume(crt)<br />
print("parity: " .. retval)</td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="execution-control" id="execution-control"></a><a href="more#execution-control-note">execution control</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="if" id="if"></a><a href="more#if-note">if</a></td>
<td>if ( 0 == $n ) {<br />
<span style="white-space: pre-wrap;">  </span>print "no hits\n"<br />
} elsif ( 1 == $n ) {<br />
<span style="white-space: pre-wrap;">  </span>print "one hit\n"<br />
} else {<br />
<span style="white-space: pre-wrap;">  </span>print "$n hits\n"<br />
}</td>
<td>if n == 0 then<br />
<span style="white-space: pre-wrap;">  </span>print("no hits")<br />
elseif n == 1 then<br />
<span style="white-space: pre-wrap;">  </span>print("one hit")<br />
else<br />
<span style="white-space: pre-wrap;">  </span>print(n .. " hits")<br />
end</td>
<td>if (n == 0) {<br />
<span style="white-space: pre-wrap;">  </span>println("no hits")<br />
}<br />
else if (n == 1) {<br />
<span style="white-space: pre-wrap;">  </span>println("one hit")<br />
}<br />
else {<br />
<span style="white-space: pre-wrap;">  </span>println(n + " hits")<br />
}</td>
</tr>
<tr>
<td><a name="while" id="while"></a><a href="more#while-note">while</a></td>
<td>while ( $i &lt; 100 ) { $i++ }</td>
<td>while i &lt; 100 do<br />
<span style="white-space: pre-wrap;">  </span>i = i + 1<br />
end</td>
<td>while (i &lt; 100) {<br />
<span style="white-space: pre-wrap;">  </span>i += 1<br />
}</td>
</tr>
<tr>
<td><a name="break-continue" id="break-continue"></a><a href="more#break-continue-note">break and continue</a></td>
<td>last next</td>
<td>break <span style="color: gray"><em>none</em></span></td>
<td>break continue</td>
</tr>
<tr>
<td><a name="for" id="for"></a><a href="more#for-note">for</a></td>
<td>for ( $i=0; $i &lt;= 10; $i++ ) {<br />
<span style="white-space: pre-wrap;">  </span>print "$i\n";<br />
}</td>
<td>for i = 0, 9 do<br />
<span style="white-space: pre-wrap;">  </span>print(i)<br />
end</td>
<td>for (i = 0; i &lt; 10; i++) {<br />
<span style="white-space: pre-wrap;">  </span>println i<br />
}</td>
</tr>
<tr>
<td><a name="stmt-modifiers" id="stmt-modifiers"></a><a href="more#stmt-modifiers-note">statement modifiers</a></td>
<td>print "positive\n" if $i &gt; 0;<br />
print "nonzero\n" unless $i == 0;</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="exceptions" id="exceptions"></a><a href="more#exceptions-note">exceptions</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="raise-exc" id="raise-exc"></a><a href="more#raise-exc-note">raise exception</a></td>
<td>die "bad arg";</td>
<td>error "bad arg"</td>
<td>throw new Exception("bad arg")</td>
</tr>
<tr>
<td><a name="catch-exc" id="catch-exc"></a><a href="more#catch-exc-note">catch exception</a></td>
<td>eval { risky };<br />
if ($@) {<br />
<span style="white-space: pre-wrap;">  </span>print "risky failed: $@\n";<br />
}</td>
<td>if not pcall(risky) then<br />
<span style="white-space: pre-wrap;">  </span>print "risky failed"<br />
end</td>
<td></td>
</tr>
<tr>
<td><a name="last-exc-global" id="last-exc-global"></a><a href="more#last-exc-global-note">global variable for last exception</a></td>
<td><span style="color: gray">$EVAL_ERROR: $@<br />
$OS_ERROR: $!<br />
$CHILD_ERROR: $?</span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="finally-ensure" id="finally-ensure"></a><a href="more#finally-ensure-note">finally/ensure</a></td>
<td></td>
<td><span style="color: gray"><em>none</em></span></td>
<td></td>
</tr>
<tr>
<td><a name="uncaught-exc" id="uncaught-exc"></a><a href="more#uncaught-exc-note">uncaught exception behavior</a></td>
<td></td>
<td><span style="color: gray"><em>stderr and exit</em></span></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="streams" id="streams"></a><a href="more#streams-note">streams</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="standard-file-handles" id="standard-file-handles"></a><a href="more#standard-file-handles-note">standard file handles</a></td>
<td>STDIN STDOUT STDERR</td>
<td>io.stdin<br />
io.stdout<br />
io.stderr</td>
<td>System.in<br />
System.out<br />
System.err</td>
</tr>
<tr>
<td><a name="read-stdin" id="read-stdin"></a><a href="more#read-stdin-note">read line from stdin</a></td>
<td>$line = &lt;STDIN&gt;;</td>
<td>line = io.stdin:read()</td>
<td></td>
</tr>
<tr>
<td><a name="eof" id="eof"></a><a href="more#eof-note">end-of-file behavior</a></td>
<td><span style="color: gray"><em>returns string without newline or</em> undef</span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="chomp" id="chomp"></a><a href="more#chomp-note">chomp</a></td>
<td>chomp $line;</td>
<td><span style="color: gray"><em>none,</em></span> read() <span style="color: gray"><em>and</em></span> lines() <span style="color: gray"><em>remove trailing newlines</em></span></td>
<td></td>
</tr>
<tr>
<td><a name="print-to-stdout" id="print-to-stdout"></a><a href="more#print-to-stdout-note">write line to stdout</a></td>
<td>print "Hello, World!\n";</td>
<td>print "Hello, World!"</td>
<td>print("Hello, World!\n")<br />
println("Hello, World!")<br />
System.out.print("Hello, World!\n")<br />
System.out.println("Hello, World!")</td>
</tr>
<tr>
<td><a name="printf" id="printf"></a><a href="more#printf-note">write formatted string to stdout</a></td>
<td>use Math::Trig 'pi';<br />
<br />
printf("%.2f\n", pi);</td>
<td></td>
<td>printf("%.2f\n", 3.1415)</td>
</tr>
<tr>
<td><a name="open-file" id="open-file"></a><a href="more#open-file-note">open file for reading</a></td>
<td>open my $f, "/etc/hosts" or die;</td>
<td>f = io.open("/tmp/foo")</td>
<td>f = new File("/etc/hosts")<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> optional traditional file handle:</span><br />
f2 = f.newInputStream()</td>
</tr>
<tr>
<td><a name="open-file-write" id="open-file-write"></a><a href="more#open-file-write-note">open file for writing</a></td>
<td>open my $f, "&gt;/tmp/test" or die;</td>
<td>f = io.open("/tmp/foo", "w")</td>
<td>f = new File("/etc/hosts")<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> optional traditional file handle:</span><br />
f2 = f.newOutputStream()</td>
</tr>
<tr>
<td><a name="file-encoding" id="file-encoding"></a><a href="more#file-encoding-note">set file handle encoding</a></td>
<td>open my $fin, "&lt;:encoding(UTF-8)", "/tmp/foo"<br />
<span style="white-space: pre-wrap;">  </span>or die;<br />
<br />
open my $fout, "&gt;:encoding(UTF-8)", "/tmp/bar"<br />
<span style="white-space: pre-wrap;">  </span>or die;</td>
<td></td>
<td>new File('/tmp/a_file.txt').withWriter('utf-8') {<br />
<span style="white-space: pre-wrap;">  </span>f -&gt; f.writeLine 'λαμβδα'<br />
}</td>
</tr>
<tr>
<td><a name="open-file-append" id="open-file-append"></a><a href="more#open-file-append-note">open file for appending</a></td>
<td>open my $f, "<span style="white-space: pre-wrap;">&gt;&gt;</span>/tmp/err.log" or die;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="close-file" id="close-file"></a><a href="more#close-file-note">close file</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>close $f or die;</td>
<td>f:close()</td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> traditional file handle:</span><br />
f2.close()</td>
</tr>
<tr>
<td><a name="close-file-implicitly" id="close-file-implicitly"></a><a href="more#close-file-implicitly-note">close file implicitly</a></td>
<td>{<br />
<span style="white-space: pre-wrap;">  </span>open(my $f, "&gt;/tmp/test") or die;<br />
<span style="white-space: pre-wrap;">  </span>print $f "lorem ipsum\n";<br />
}</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="io-err" id="io-err"></a><a href="more#io-err-note">i/o error</a></td>
<td><span style="color: gray"><em>return false value</em></span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="encoding-err" id="encoding-err"></a><a href="more#encoding-err-note">encoding error</a></td>
<td><span style="color: gray"><em>emit warning and replace bad byte with 4 character \xHH sequence</em></span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="read-line" id="read-line"></a><a href="more#read-line-note">read line</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>$line = &lt;$f&gt;;</td>
<td>f:read()</td>
<td></td>
</tr>
<tr>
<td><a name="file-iter" id="file-iter"></a><a href="more#file-iter-note">iterate over file by line</a></td>
<td>while ($line = &lt;$f&gt;) {<br />
<span style="white-space: pre-wrap;">  </span>print $line;<br />
}</td>
<td>for s in f:lines() do<br />
<span style="white-space: pre-wrap;">  </span><span style="color: gray"><em>use s</em></span><br />
end</td>
<td></td>
</tr>
<tr>
<td><a name="read-file-array" id="read-file-array"></a><a href="more#read-file-array-note">read file into array of strings</a></td>
<td>@a = &lt;$f&gt;;</td>
<td></td>
<td>a = f.readLines()</td>
</tr>
<tr>
<td><a name="read-file-str" id="read-file-str"></a><a href="more#read-file-str-note">read file into string</a></td>
<td>$s = do { local $/; &lt;$f&gt; };</td>
<td>s = f:read("*a")</td>
<td>s = f.text</td>
</tr>
<tr>
<td><a name="write-file" id="write-file"></a><a href="more#write-file-note">write string</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>print $f "lorem ipsum";</td>
<td>f:write("lorem ipsum")</td>
<td></td>
</tr>
<tr>
<td><a name="write-line" id="write-line"></a><a href="more#write-line-note">write line</a></td>
<td>print $f "lorem ipsum\n";</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="flush-file" id="flush-file"></a><a href="more#flush-file-note">flush file handle</a></td>
<td>use IO::Handle;<br />
<br />
$f-&gt;flush();</td>
<td>f:flush()</td>
<td></td>
</tr>
<tr>
<td><a name="eof-test" id="eof-test"></a><a href="more#eof-test-note">end-of-file test</a></td>
<td>eof($f)</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="seek" id="seek"></a><a href="more#seek-note">file handle position</a><br />
<span style="color: gray"><em>get, set</em></span></td>
<td>tell($f)<br />
seek($f, 0, SEEK_SET);</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="open-tmp-file" id="open-tmp-file"></a><a href="more#open-tmp-file-note">open temporary file</a></td>
<td>use File::Temp;<br />
<br />
$f = File::Temp-&gt;new();<br />
<br />
print $f "lorem ipsum\n";<br />
<br />
print "tmp file: ";<br />
print $f-&gt;filename . "\n";<br />
<br />
close $f or die;<br />
<br />
<span style="color: gray"># file is removed when file handle goes<br />
# out of scope</span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="in-memory-stream" id="in-memory-stream"></a><a href="more#in-memory-stream-note">in memory stream</a></td>
<td>my ($f, $s);<br />
open($f, "&gt;", \$s);<br />
print $f "lorem ipsum\n";<br />
$s;</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="files" id="files"></a><a href="more#files-note">files</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="file-test" id="file-test"></a><a href="more#file-test-note">file exists test, file regular test</a></td>
<td>-e "/etc/hosts"<br />
-f "/etc/hosts"</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>f = new File('/etc/hosts')<br />
<br />
f.exists()<br />
f.isFile()</td>
</tr>
<tr>
<td><a name="file-size" id="file-size"></a><a href="more#file-size-note">file size</a></td>
<td>-s "/etc/hosts"</td>
<td></td>
<td>f = new File('/etc/hosts')<br />
<br />
f.length()</td>
</tr>
<tr>
<td><a name="readable-writable-executable" id="readable-writable-executable"></a><a href="more#readable-writable-executable-note">is file readable, writable, executable</a></td>
<td>-r "/etc/hosts"<br />
-w "/etc/hosts"<br />
-x "/etc/hosts"</td>
<td></td>
<td>f = new File('etc/hosts')<br />
<br />
f.canRead()<br />
f.canWrite()<br />
f.canExecute()</td>
</tr>
<tr>
<td><a name="chmod" id="chmod"></a><a href="more#chmod-note">set file permissions</a></td>
<td>chmod 0755, "/tmp/foo";</td>
<td><span style="color: gray"><em>none</em></span></td>
<td>f = new File("/tmp/foo")<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> set owner permissions:</span><br />
f.setReadable(true)<br />
f.setWritable(true)<br />
f.setExecutable(true)<br />
<br />
<span style="color: gray"><span style="white-space: pre-wrap;">//</span> set owner/group/other permissions:</span><br />
f.setReadable(true, false)<br />
f.setWritable(true, false)<br />
f.setExecutable(true, false)</td>
</tr>
<tr>
<td><a name="last-modification-time" id="last-modification-time"></a><a href="more#last-modification-time-note">last modification time</a></td>
<td>my @data = stat('/etc/passwd');<br />
<br />
<span style="color: gray"># unix epoch:</span><br />
my $t = $data['mtime'];</td>
<td></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> milliseconds since Unix epoch:</span><br />
new File("/etc/passwd").lastModified()</td>
</tr>
<tr>
<td><a name="file-cp-rm-mv" id="file-cp-rm-mv"></a><a href="more#file-cp-rm-mv-note">copy file, remove file, rename file</a></td>
<td>use File::Copy;<br />
<br />
copy("/tmp/foo", "/tmp/bar");<br />
unlink "/tmp/foo";<br />
move("/tmp/bar", "/tmp/foo");</td>
<td><span style="color: gray"><em>none</em></span></td>
<td><span style="color: gray"><em>??</em></span><br />
new File("/tmp/foo").delete()<br />
new File("/tmp/bar").renameTo("/tmp/foo")</td>
</tr>
<tr>
<td><a name="symlink" id="symlink"></a><a href="more#symlink-note">create symlink, symlink test, readlink</a></td>
<td>symlink "/etc/hosts", "/tmp/hosts";<br />
-l "/etc/hosts"<br />
readlink "/tmp/hosts"</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="tmpfile" id="tmpfile"></a><a href="more#tmpfile-note">generate unused file name</a></td>
<td>use File::Temp;<br />
<br />
$f = File::Temp-&gt;new(DIR=&gt;"/tmp",<br />
<span style="white-space: pre-wrap;">  </span>TEMPLATE=&gt;"fooXXXXX",<br />
<span style="white-space: pre-wrap;">  </span>CLEANUP=&gt;0);<br />
$path = $f-&gt;filename;</td>
<td>f = io.tmpfile()<br />
f:write("lorem ipsum\n")<br />
f:close()<br />
<span style="color: gray"><em>??</em></span></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> args are prefix and suffix:</span><br />
f = File.createTempFile("foo", ".txt")</td>
</tr>
<tr>
<th colspan="4"><a name="file-fmt" id="file-fmt"></a><a href="more#file-fmt-note">file formats</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="parse-csv" id="parse-csv"></a><a href="more#parse-csv-note">parse csv</a></td>
<td># cpan -i Text::CSV<br />
use Text::CSV;<br />
<br />
my $csv = Text::CSV-&gt;new or die;<br />
open my $f, $ARGV[0] or die;<br />
while (my $row = $csv-&gt;getline($f)) {<br />
<span style="white-space: pre-wrap;">  </span>print join("\t", @$row) . "\n";<br />
}</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="generate-csv" id="generate-csv"></a><a href="more#generate-csv-note">generate csv</a></td>
<td><span style="color: gray"># cpan -i Text::CSV</span><br />
use Text::CSV;<br />
<br />
my $csv = Text::CSV-&gt;new or die;<br />
$csv-&gt;eol ("\r\n");<br />
open my $f, "&gt;nums.csv" or die;<br />
$csv-&gt;print($f, ["one", "une", "uno"]);<br />
$csv-&gt;print($f, ["two", "deux", "dos"]);<br />
$f-&gt;close or die;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="parse-json" id="parse-json"></a><a href="more#parse-json-note">parse json</a></td>
<td><span style="color: gray"># cpan -i JSON</span><br />
use JSON;<br />
<br />
$json = JSON-&gt;new-&gt;allow_nonref;<br />
$data = $json-&gt;decode('{"t": 1, "f": 0}');</td>
<td></td>
<td>import groovy.json.JsonSlurper<br />
<br />
jsonSlurper = new JsonSlurper()<br />
data = jsonSlurper.parseText('{"t": 1, "f": 0}')</td>
</tr>
<tr>
<td><a name="generate-json" id="generate-json"></a><a href="more#generate-json-note">generate json</a></td>
<td><span style="color: gray"># cpan -i JSON</span><br />
use JSON;<br />
<br />
$json = JSON-&gt;new-&gt;allow_nonref;<br />
$data = {t =&gt; 1, f =&gt; 0};<br />
$s = $json-&gt;encode($data);</td>
<td></td>
<td>import groovy.json.JsonOutput<br />
<br />
JsonOutput.toJson(["t": 1, "f": 0])</td>
</tr>
<tr>
<td><a name="parse-xml" id="parse-xml"></a><a href="more#parse-xml-note">parse xml</a></td>
<td><span style="color: gray"># cpan -i XML::XPath</span><br />
use XML::XPath;<br />
<br />
my $xml = "&lt;a&gt;&lt;b&gt;&lt;c&gt;foo&lt;/c&gt;&lt;/b&gt;&lt;/a&gt;";<br />
<br />
<span style="color: gray"># fatal error if XML not well-formed</span><br />
my $doc = XML::XPath-&gt;new(xml =&gt; $xml);<br />
<br />
my $nodes = $doc-&gt;find("/a/b/c");<br />
print $nodes-&gt;size . "\n";<br />
<br />
$node = $nodes-&gt;get_node(0);<br />
print $node-&gt;string_value . "\n";<br />
print $node-&gt;getAttribute("ref") . "\n";</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="generate-xml" id="generate-xml"></a><a href="more#generate-xml-note">generate xml</a></td>
<td><span style="color: gray"># cpan -i XML::Writer</span><br />
use XML::Writer;<br />
<br />
my $writer = XML::Writer-&gt;new(<br />
OUTPUT =&gt; STDOUT);<br />
$writer-&gt;startTag("a");<br />
$writer-&gt;startTag("b", id =&gt; "123");<br />
$writer-&gt;characters("foo");<br />
$writer-&gt;endTag("b");<br />
$writer-&gt;endTag("a");<br />
<br />
<span style="color: gray"># &lt;a&gt;&lt;b id="123"&gt;foo&lt;/b&gt;&lt;/a&gt;:</span><br />
$writer-&gt;end;</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="directories" id="directories"></a><a href="more#directories-note">directories</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="working-dir" id="working-dir"></a><a href="more#working-dir-note">working directory</a><br />
<span style="color: gray"><em>get and set</em></span></td>
<td>use Cwd;<br />
<br />
my $old_dir = cwd();<br />
<br />
chdir("/tmp");</td>
<td></td>
<td>System.getProperty("user.dir")<br />
<br />
<span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="build-pathname" id="build-pathname"></a><a href="more#build-pathname-note">build pathname</a></td>
<td>use File::Spec;<br />
<br />
File::Spec-&gt;catfile("/etc", "hosts")</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="dirname-basename" id="dirname-basename"></a><a href="more#dirname-basename-note">dirname and basename</a></td>
<td>use File::Basename;<br />
<br />
print dirname("/etc/hosts");<br />
print basename("/etc/hosts");</td>
<td></td>
<td>f = new File("/etc/hosts")<br />
f.getParent()<br />
f.getName()</td>
</tr>
<tr>
<td><a name="absolute-pathname" id="absolute-pathname"></a><a href="more#absolute-pathname-note">absolute pathname</a></td>
<td>use Cwd;<br />
<br />
<span style="color: gray"># symbolic links are resolved:</span><br />
Cwd::abs_path("foo")<br />
Cwd::abs_path("/foo")<br />
Cwd::abs_path("../foo")<br />
Cwd::abs_path(".")</td>
<td></td>
<td>new File("foo").getAbsolutePath()<br />
new File("/foo").getAbsolutePath()<br />
new File("../foo").getCanonicalPath()<br />
new File(".").getCanonicalPath()</td>
</tr>
<tr>
<td><a name="dir-iter" id="dir-iter"></a><a href="more#dir-iter-note">iterate over directory by file</a></td>
<td>opendir(my $dh, $ARGV[0]);<br />
<br />
while (my $file = readdir($dh)) {<br />
<span style="white-space: pre-wrap;">  </span>print $file . "\n";<br />
}<br />
<br />
closedir($dh);</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="glob" id="glob"></a><a href="more#glob-note">glob paths</a></td>
<td>while ( &lt;/etc/*&gt; ) {<br />
<span style="white-space: pre-wrap;">  </span>print $_ . "\n";<br />
}</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="mkdir" id="mkdir"></a><a href="more#mkdir-note">make directory</a></td>
<td>use File::Path 'make_path';<br />
<br />
make_path "/tmp/foo/bar";</td>
<td></td>
<td>new File("/tmp/foo/bar").mkdirs()</td>
</tr>
<tr>
<td><a name="recursive-cp" id="recursive-cp"></a><a href="more#recursive-cp-note">recursive copy</a></td>
<td><span style="color: gray"># cpan -i File::Copy::Recursive</span><br />
use File::Copy::Recursive 'dircopy';<br />
<br />
dircopy "/tmp/foodir",<br />
<span style="white-space: pre-wrap;">  </span>"/tmp/bardir";</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="rmdir" id="rmdir"></a><a href="more#rmdir-note">remove empty directory</a></td>
<td>rmdir "/tmp/foodir";</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="rm-rf" id="rm-rf"></a><a href="more#rm-rf-note">remove directory and contents</a></td>
<td>use File::Path 'remove_tree';<br />
<br />
remove_tree "/tmp/foodir";</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="dir-test" id="dir-test"></a><a href="more#dir-test-note">directory test</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>-d "/tmp"</td>
<td></td>
<td>new File("/tmp").isDirectory()</td>
</tr>
<tr>
<td><a name="unused-dir" id="unused-dir"></a><a href="more#unused-dir-note">generate unused directory</a></td>
<td>use File::Temp qw(tempdir);<br />
<br />
$path = tempdir(DIR=&gt;"/tmp",<br />
<span style="white-space: pre-wrap;">  </span>CLEANUP=&gt;0);</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="system-tmp-dir" id="system-tmp-dir"></a><a href="more#system-tmp-dir-note">system temporary file directory</a></td>
<td>use File::Spec;<br />
<br />
File::Spec-&gt;tmpdir</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="processes-environment" id="processes-environment"></a><a href="more#processes-environment-note">processes and environment</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="cmd-line-arg" id="cmd-line-arg"></a><a href="more#cmd-line-arg-note">command line arguments</a></td>
<td>@ARGV</td>
<td># arg<br />
arg[0]<br />
arg[1]<br />
<span style="color: gray"><em>…</em></span></td>
<td>args.size()<br />
args[0]<br />
args[1]<br />
…</td>
</tr>
<tr>
<td><a name="program-name" id="program-name"></a><a href="more#program-name-note">program name</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>$0</td>
<td></td>
<td><span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="env-var" id="env-var"></a><a href="more#env-var-note">environment variable</a><br />
<span style="color: gray"><em>get, set</em></span></td>
<td>$ENV{"HOME"}<br />
<br />
$ENV{"PATH") = "/bin";</td>
<td>os.getenv("HOME")</td>
<td>System.getenv("HOME")</td>
</tr>
<tr>
<td><a name="pid" id="pid"></a><a href="more#pid-note">get pid, parent pid</a></td>
<td>$$<br />
getppid</td>
<td></td>
<td><span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="user-id-name" id="user-id-name"></a><a href="more#user-id-name-note">get user id and name</a></td>
<td>$&lt;<br />
getpwuid($&lt;)</td>
<td></td>
<td><span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="exit" id="exit"></a><a href="more#exit-note">exit</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>exit 0;</td>
<td>os.exit(0)</td>
<td>System.exit(0)</td>
</tr>
<tr>
<td><a name="signal-handler" id="signal-handler"></a><a href="more#signal-handler-note">set signal handler</a></td>
<td>$SIG{INT} = sub {<br />
<span style="white-space: pre-wrap;">  </span>die "exiting…\n";<br />
};</td>
<td></td>
<td><span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="exec-test" id="exec-test"></a><a href="more#exec-test-note">executable test</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>-x "/bin/ls"</td>
<td></td>
<td>new File("/bin/ls").canExecute()</td>
</tr>
<tr>
<td><a name="external-cmd" id="external-cmd"></a><a href="more#external-cmd-note">external command</a></td>
<td>system("ls -l /tmp") == 0 or<br />
<span style="white-space: pre-wrap;">  </span>die "ls failed";</td>
<td>os.execute("ls")</td>
<td>buffer = new StringBuffer()<br />
p = 'ls'.execute()<br />
p.waitForProcessOutput(buffer, buffer)<br />
buffer.toString()</td>
</tr>
<tr>
<td><a name="shell-esc-external-cmd" id="shell-esc-external-cmd"></a><a href="more#shell-esc-external-cmd-note">shell-escaped external command</a></td>
<td>$path = &lt;&gt;;<br />
chomp($path);<br />
system("ls", "-l", $path) == 0 or<br />
<span style="white-space: pre-wrap;">  </span>die "ls failed";</td>
<td></td>
<td><span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="cmd-subst" id="cmd-subst"></a><a href="more#cmd-subst-note">command substitution</a></td>
<td>my $files = ‘ls -l /tmp`;<br />
<span style="color: gray"># or</span><br />
my $files = qx(ls);</td>
<td>f = io.popen("ls")<br />
s = f:read("*a")</td>
<td><span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<th colspan="4"><a name="option-parsing" id="option-parsing"></a><a href="more#option-parsing-note">option parsing</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="cmd-line-opt" id="cmd-line-opt"></a><a href="more#cmd-line-opt-note">command line options</a></td>
<td>use Getopt::Long;<br />
<br />
my ($file, $help, $verbose);<br />
<br />
my $usage =<br />
<span style="white-space: pre-wrap;">  </span>"usage: $0 [-f FILE] [-v] [ARG …]\n";<br />
<br />
if (!GetOptions("file=s" =&gt; \$file,<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>"help" =&gt; \$help,<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>"verbose" =&gt; \$verbose)) {<br />
<span style="white-space: pre-wrap;">  </span>print $usage;<br />
<span style="white-space: pre-wrap;">  </span>exit 1;<br />
}<br />
<br />
if ($help) {<br />
<span style="white-space: pre-wrap;">  </span>print $usage;<br />
<span style="white-space: pre-wrap;">  </span>exit 0;<br />
}<br />
<br />
<span style="color: gray"># After call to GetOptions() only<br />
# positional arguments are in @ARGV.<br />
#<br />
# Options can follow positional arguments.<br />
#<br />
# Long options can be preceded by one or two<br />
# hyphens. Single letters can be used if<br />
# only one long option begins with that<br />
# letter.<br />
#<br />
# Single letter options cannot be bundled<br />
# after a single hyphen.<br />
#<br />
# Single letter options must be separated<br />
# from an argument by a space or =.</span></td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="libraries-namespaces" id="libraries-namespaces"></a><a href="more#libraries-namespaces-note">libraries and namespaces</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="compile-lib" id="compile-lib"></a><a href="more#compile-lib-note">compile library</a></td>
<td><span style="color: gray"><em>none</em></span></td>
<td><span style="color: gray"><em>none</em></span></td>
<td>$ cat Foo.groovy<br />
class Foo {<br />
<span style="white-space: pre-wrap;">  </span>static int add(int a, int b) {<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>a + b<br />
<span style="white-space: pre-wrap;">  </span>}<br />
}<br />
<br />
$ groovyc foo.groovy</td>
</tr>
<tr>
<td><a name="load-lib" id="load-lib"></a><a href="more#load-lib-note">load library</a></td>
<td>require ’Foo.pm';<br />
<br />
<span style="color: gray"># searches @INC for Foo.pm:</span><br />
require Foo;</td>
<td>require 'foo'<br />
add(3,7)</td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> import Foo from Foo.groovy:</span><br />
import Foo</td>
</tr>
<tr>
<td><a name="load-lib-subdir" id="load-lib-subdir"></a><a href="more#load-lib-subdir-note">load library in subdirectory</a></td>
<td>require 'Foo/Bar.pm';<br />
<br />
require Foo::Bar;</td>
<td></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> import Foo from bar/Foo.groovy:</span><br />
import bar.Foo</td>
</tr>
<tr>
<td><a name="hot-patch" id="hot-patch"></a><a href="more#hot-patch-note">hot patch</a></td>
<td>do 'Foo.pm';</td>
<td></td>
<td><span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="load-err" id="load-err"></a><a href="more#load-err-note">load error</a></td>
<td><span style="color: gray"><em>fatal error if library not found or if last expression in library does not evaluate as true; fatal error parsing library propagates to client</em></span></td>
<td></td>
<td>org.codehaus.groovy.control.MultipleCompilationErrorsException</td>
</tr>
<tr>
<td><a name="main-in-lib" id="main-in-lib"></a><a href="more#main-in-lib-note">main routine in library</a></td>
<td>unless (caller) {<br />
<span style="white-space: pre-wrap;">  </span><span style="color: gray"><em>code</em></span><br />
}</td>
<td></td>
<td>class Foo {<br />
<span style="white-space: pre-wrap;">  </span>static void main(String… args) {<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>println "main was called"<br />
<span style="white-space: pre-wrap;">  </span>}<br />
}</td>
</tr>
<tr>
<td><a name="lib-path" id="lib-path"></a><a href="more#lib-path-note">library path</a></td>
<td>@INC<br />
<br />
push @INC, "/some/path";</td>
<td>package.path</td>
<td><span style="color: gray"><em>none</em></span></td>
</tr>
<tr>
<td><a name="lib-path-env" id="lib-path-env"></a><a href="more#lib-path-env-note">library path environment variable</a></td>
<td>$ PERL5LIB=~/lib perl foo.pl</td>
<td>LUA_PATH</td>
<td>$ CLASSPATH=lib groovy main.groovy</td>
</tr>
<tr>
<td><a name="lib-path-cmd-line" id="lib-path-cmd-line"></a><a href="more#lib-path-cmd-line-note">library path command line option</a></td>
<td>$ perl -I ~/lib foo.pl</td>
<td></td>
<td>$ groovy -cp lib main.groovy</td>
</tr>
<tr>
<td><a name="simple-global-id" id="simple-global-id"></a><a href="more#simple-global-id-note">simple global identifiers</a></td>
<td><span style="color: gray"><em>none</em></span></td>
<td></td>
<td><span style="color: gray"><em>only class identifiers are global</em></span></td>
</tr>
<tr>
<td><a name="multiple-label-id" id="multiple-label-id"></a><a href="more#multiple-label-id-note">multiple label identifiers</a></td>
<td><span style="color: gray"><em>all identifiers not declared with</em> my</span></td>
<td></td>
<td><span style="color: gray"><em>Classes defined inside a file with a package declaration at the top.</em></span></td>
</tr>
<tr>
<td><a name="namespace-label-separator" id="namespace-label-separator"></a><a href="more#namespace-label-separator-note">namespace label separator</a></td>
<td>Foo::Bar::baz();</td>
<td>.</td>
<td>foo.bar.Baz()</td>
</tr>
<tr>
<td><a name="namespace-decl" id="namespace-decl"></a><a href="more#namespace-decl-note">namespace declaration</a></td>
<td>package Foo;<br />
require Exporter;<br />
our @ISA = ("Exporter");<br />
our @EXPORT_OK = qw(bar baz);</td>
<td>module</td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> all non-classes in namespace of a class:</span><br />
class Foo {<br />
<br />
}</td>
</tr>
<tr>
<td><a name="subnamespace-decl" id="subnamespace-decl"></a><a href="more#subnamespace-decl-note">subnamespace declaration</a></td>
<td>package Foo::Bar;</td>
<td></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> define class foo.Bar:</span><br />
package foo<br />
<br />
class Bar {<br />
<br />
}</td>
</tr>
<tr>
<td><a name="import-def" id="import-def"></a><a href="more#import-def-note">import definitions</a></td>
<td><span style="color: gray"># bar and baz must be in<br />
# @EXPORT or @EXPORT_OK:</span><br />
use Foo qw(bar baz);</td>
<td></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> all imports are unqualified:</span><br />
import foo.Bar<br />
import foo.Baz</td>
</tr>
<tr>
<td><a name="import-namespace" id="import-namespace"></a><a href="more#import-namespace-note">import all definitions in namespace</a></td>
<td><span style="color: gray"># imports symbols in @EXPORT:</span><br />
use Foo;</td>
<td></td>
<td><span style="color: gray"><span style="white-space: pre-wrap;">//</span> import all classes in foo:</span><br />
import foo.*</td>
</tr>
<tr>
<td><a name="shadow-avoidance" id="shadow-avoidance"></a><a href="more#shadow-avoidance-note">shadow avoidance</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td></td>
<td></td>
<td>import java.math.BigInteger as BigInt</td>
</tr>
<tr>
<td><a name="pkg-management" id="pkg-management"></a><a href="more#pkg-management-note">list installed packaged, install a package</a></td>
<td>$ perldoc perllocal<br />
$ cpan -i Moose</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="objects" id="objects"></a><a href="more#objects-note">objects</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="def-class" id="def-class"></a><a href="more#def-class-note">define class</a></td>
<td>package Int;<br />
<br />
sub new {<br />
<span style="white-space: pre-wrap;">  </span>my $class = shift;<br />
<span style="white-space: pre-wrap;">  </span>my $v = $_[0] <span style="white-space: pre-wrap;">||</span> 0;<br />
<span style="white-space: pre-wrap;">  </span>my $self = {value =&gt; $v};<br />
<span style="white-space: pre-wrap;">  </span>bless $self, $class;<br />
<span style="white-space: pre-wrap;">  </span>$self;<br />
}<br />
<br />
sub value {<br />
<span style="white-space: pre-wrap;">  </span>my $self = shift;<br />
<span style="white-space: pre-wrap;">  </span>if ( @_ &gt; 0 ) {<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>$self-&gt;{'value'} = shift;<br />
<span style="white-space: pre-wrap;">  </span>}<br />
<span style="white-space: pre-wrap;">  </span>$self-&gt;{'value'};<br />
}</td>
<td></td>
<td>class Int {<br />
<span style="white-space: pre-wrap;">  </span>public int value<br />
<span style="white-space: pre-wrap;">  </span>Int (int n) {<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>value = n<br />
<span style="white-space: pre-wrap;">  </span>}<br />
}</td>
</tr>
<tr>
<td><a name="create-obj" id="create-obj"></a><a href="more#create-obj-note">create object</a></td>
<td>my $i = new Int(); <span style="color: gray"># or</span><br />
my $i = Int-&gt;new();</td>
<td></td>
<td>o = new Int(3)</td>
</tr>
<tr>
<td><a name="blank-obj" id="blank-obj"></a><a href="more#blank-obj-note">create blank object</a></td>
<td></td>
<td>o = {}</td>
<td></td>
</tr>
<tr>
<td><a name="instance-var-visibility" id="instance-var-visibility"></a><a href="more#instance-var-visibility-note">instance variable visibility</a></td>
<td><span style="color: gray"><em>private; getters and setters must be explicitly defined</em></span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="obj-literal" id="obj-literal"></a><a href="more#obj-literal-note">object literal</a></td>
<td></td>
<td>o = {<br />
<span style="white-space: pre-wrap;">  </span>score=21,<br />
<span style="white-space: pre-wrap;">  </span>doubleScore=function(self)<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>return 2*self.score<br />
<span style="white-space: pre-wrap;">  </span>end<br />
}</td>
<td></td>
</tr>
<tr>
<td><a name="set-attr" id="set-attr"></a><a href="more#set-attr-note">set attribute</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>$i-&gt;value($v + 1);</td>
<td>o.score = 21</td>
<td>o.value = 4</td>
</tr>
<tr>
<td><a name="get-attr" id="get-attr"></a><a href="more#get-attr-note">get attribute</a></td>
<td>my $v = $i-&gt;value;</td>
<td>if o.score == 21 then<br />
<span style="white-space: pre-wrap;">  </span>print("Blackjack!")<br />
end</td>
<td>o.value</td>
</tr>
<tr>
<td><a name="def-method" id="def-method"></a><a href="more#def-method-note">define method</a></td>
<td>sub plus {<br />
<span style="white-space: pre-wrap;">  </span>my $self = shift;<br />
<span style="white-space: pre-wrap;">  </span>$self-&gt;value + $_[0];<br />
}</td>
<td>function o.doubleScore(self)<br />
<span style="white-space: pre-wrap;">  </span>return 2 * self.score<br />
end</td>
<td></td>
</tr>
<tr>
<td><a name="invoke-method" id="invoke-method"></a><a href="more#invoke-method-note">invoke method</a></td>
<td>$i-&gt;plus(7)</td>
<td>print("Answer: " .. o:doubleScore())</td>
<td></td>
</tr>
<tr>
<td><a name="method-missing" id="method-missing"></a><a href="more#method-missing-note">handle undefined method invocation</a></td>
<td>our $AUTOLOAD;<br />
<br />
sub AUTOLOAD {<br />
<span style="white-space: pre-wrap;">  </span>my $self = shift;<br />
<span style="white-space: pre-wrap;">  </span>my $argc = scalar(@_);<br />
<span style="white-space: pre-wrap;">  </span>print "no def: $AUTOLOAD"<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>. " arity: $argc\n";<br />
}</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="def-class-method" id="def-class-method"></a><a href="more#def-class-method-note">define class method</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="invoke-class-method" id="invoke-class-method"></a><a href="more#invoke-class-method-note">invoke class method</a></td>
<td>Counter-&gt;instances();</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="def-class-var" id="def-class-var"></a><a href="more#def-class-var-note">define class variable</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="get-set-class-var" id="get-set-class-var"></a><a href="more#get-set-class-var-note">get and set class variable</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="inheritance-polymorphism" id="inheritance-polymorphism"></a><a href="more#inheritance-polymorphism-note">inheritance and polymorphism</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="subclass" id="subclass"></a><a href="more#subclass-note">subclass</a></td>
<td>package Counter;<br />
<br />
our @ISA = "Int";<br />
<br />
my $instances = 0;<br />
<br />
sub new {<br />
<span style="white-space: pre-wrap;">  </span>my $class = shift;<br />
<span style="white-space: pre-wrap;">  </span>my $self = Int-&gt;new(@_);<br />
<span style="white-space: pre-wrap;">  </span>$instances += 1;<br />
<span style="white-space: pre-wrap;">  </span>bless $self, $class;<br />
<span style="white-space: pre-wrap;">  </span>$self;<br />
}<br />
<br />
sub incr {<br />
<span style="white-space: pre-wrap;">  </span>my $self = shift;<br />
<span style="white-space: pre-wrap;">  </span>$self-&gt;value($self-&gt;value + 1);<br />
}<br />
<br />
sub instances {<br />
<span style="white-space: pre-wrap;">  </span>$instances;<br />
}</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="reflection" id="reflection"></a><a href="more#reflection-note">reflection</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="inspect-type" id="inspect-type"></a><a href="more#inspect-type-note">inspect type</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>ref([]) eq "ARRAY"<br />
<br />
<span style="color: gray"><em>returns empty string if argument not a reference; returns package name for objects</em></span></td>
<td>type(o)</td>
<td>o.class<br />
o.getClass()</td>
</tr>
<tr>
<td><a name="basic-types" id="basic-types"></a><a href="more#basic-types-note">basic types</a></td>
<td>SCALAR<br />
ARRAY<br />
HASH<br />
CODE<br />
REF<br />
GLOB<br />
LVALUE<br />
FORMAT<br />
IO<br />
VSTRING<br />
Regexp</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="inspect-class" id="inspect-class"></a><a href="more#inspect-class-note">inspect class</a></td>
<td>ref($o) eq "Foo"</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="has-method" id="has-method"></a><a href="more#has-method-note">has method?</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>$o-&gt;can("reverse")</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="msg-passing" id="msg-passing"></a><a href="more#msg-passing-note">message passing</a></td>
<td>for $i (0..10) {<br />
<span style="white-space: pre-wrap;">  </span>$meth = "phone$i";<br />
<span style="white-space: pre-wrap;">  </span>$o-&gt;$meth(undef);<br />
}</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="eval" id="eval"></a><a href="more#eval-note">eval</a><br />
<span style="white-space: pre-wrap;"> </span></td>
<td>while(&lt;&gt;) {<br />
<span style="white-space: pre-wrap;">  </span>print ((eval), "\n");<br />
}</td>
<td>assert(loadstring("x = 1+1"))()</td>
<td></td>
</tr>
<tr>
<td><a name="methods" id="methods"></a><a href="more#methods-note">list object methods</a></td>
<td></td>
<td></td>
<td>"lorem".metaClass.methods</td>
</tr>
<tr>
<td><a name="attributes" id="attributes"></a><a href="more#attributes-note">list object attributes</a></td>
<td>keys %$o;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="loaded-lib" id="loaded-lib"></a><a href="more#loaded-lib-note">list loaded libraries</a></td>
<td><span style="color: gray"># relative to directory in lib path:</span><br />
keys %INC<br />
<br />
<span style="color: gray"># absolute path:</span><br />
values %INC</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="loaded-namespaces" id="loaded-namespaces"></a><a href="more#loaded-namespaces-note">list loaded namespaces</a></td>
<td>grep { $_ =~ /::/ } keys %::</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="inspect-namespace" id="inspect-namespace"></a><a href="more#inspect-namespace-note">inspect namespace</a></td>
<td>keys %URI::</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="pretty-print" id="pretty-print"></a><a href="more#pretty-print-note">pretty print</a></td>
<td>use Data::Dumper;<br />
<br />
%d = (lorem=&gt;1, ipsum=&gt;[2, 3]);<br />
<br />
print Dumper(\%d);</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="src-line-file" id="src-line-file"></a><a href="more#src-line-file-note">source line number and file name</a></td>
<td><span style="white-space: pre-wrap;">__LINE__</span><br />
<span style="white-space: pre-wrap;">__FILE__</span></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="cmd-line-doc" id="cmd-line-doc"></a><a href="more#cmd-line-doc-note">command line documentation</a></td>
<td>$ perldoc Math::Trig</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="net-web" id="net-web"></a><a href="more#net-web-note">net and web</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="hostname-ip" id="hostname-ip"></a><a href="more#hostname-ip-note">get local hostname, dns lookup, reverse dns lookup</a></td>
<td>use Sys::Hostname;<br />
use IO::Socket;<br />
<br />
$host = hostname;<br />
$ip = inet_ntoa(<br />
<span style="white-space: pre-wrap;">  </span>(gethostbyname(hostname))[4]);<br />
$host2 = (gethostbyaddr(<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>inet_aton("10.45.234.23"),<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">  </span>AF_INET))[0];</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="http-get" id="http-get"></a><a href="more#http-get-note">http get</a></td>
<td>use LWP::UserAgent;<br />
<br />
$url = <span style="white-space: pre-wrap;">"http://www.google.com";</span><br />
$r = HTTP::Request-&gt;new(GET=&gt;$url);<br />
$ua = LWP::UserAgent-&gt;new;<br />
$resp = $ua-&gt;request($r);<br />
my $s = $resp-&gt;content();</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="http-post" id="http-post"></a><a href="more#http-post-note">http post</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="absolute-url" id="absolute-url"></a><a href="more#absolute-url-note">absolute url</a><br />
<span style="color: gray"><em>from base and relative url</em></span></td>
<td>use URI;<br />
<br />
URI-&gt;new_abs("analytics",<br />
<span style="white-space: pre-wrap;">  </span><span style="white-space: pre-wrap;">"http://google.com"</span>);</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="parse-url" id="parse-url"></a><a href="more#parse-url-note">parse url</a></td>
<td>use URI;<br />
<br />
$url = <span style="white-space: pre-wrap;">"http://foo.com:80/baz?q=3#baz";</span><br />
$up = URI-&gt;new($url);<br />
<br />
$protocol = $up-&gt;scheme;<br />
$hostname = $up-&gt;host;<br />
$port = $up-&gt;port;<br />
$path = $up-&gt;path;<br />
$query_str = $up-&gt;query;<br />
$fragment = $up-&gt;fragment;<br />
<br />
<span style="color: gray"># flat list of alternating keys and<br />
# values:</span><br />
@params = $up-&gt;query_form();</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="url-encode" id="url-encode"></a><a href="more#url-encode-note">url encode/decode</a></td>
<td>use CGI;<br />
<br />
CGI::escape("lorem ipsum?")<br />
CGI::unescape("lorem%20ipsum%3F")</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="base64" id="base64"></a><a href="more#base64-note">base64 encode/decode</a></td>
<td>use MIME::Base64;<br />
<br />
open my $f, "&lt;", "foo.png";<br />
my $s = do { local $/; &lt;$f&gt; };<br />
my $b64 = encode_base64($s);<br />
my $s2 = decode_base64($b64);</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="unit-tests" id="unit-tests"></a><a href="more#unit-tests-note">unit tests</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="test-class" id="test-class"></a><a href="more#test-class-note">test class</a></td>
<td><span style="color: gray"># cpan -i Test::Class Test::More</span><br />
package TestFoo;<br />
use Test::Class;<br />
use Test::More;<br />
use base qw(Test::Class);<br />
<br />
sub test_01 : Test {<br />
<span style="white-space: pre-wrap;">  </span>ok(1, "not true!");<br />
}<br />
<br />
1;</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="run-test" id="run-test"></a><a href="more#run-test-note">run tests, run test method</a></td>
<td>$ cat TestFoo.t<br />
use TestFoo;<br />
Test::Class-&gt;runtests;<br />
<br />
$ perl ./TestFoo.t</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="assert-equal" id="assert-equal"></a><a href="more#assert-equal-note">equality assertion</a></td>
<td>my $s = "do re me";<br />
is($s, "do re me");</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="assert-approx" id="assert-approx"></a><a href="more#assert-approx-note">approximate assertion</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="assert-regex" id="assert-regex"></a><a href="more#assert-regex-note">regex assertion</a></td>
<td>my $s = "lorem ipsum";<br />
like($s, qr/lorem/);</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="assert-exc" id="assert-exc"></a><a href="more#assert-exc-note">exception assertion</a></td>
<td>use Test::Fatal;<br />
<br />
ok(exception { 1 / 0 });</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="test-setup" id="test-setup"></a><a href="more#test-setup-note">setup</a></td>
<td><span style="color: gray"># in class TestFoo:</span><br />
sub make_fixture : Test(setup) {<br />
<span style="white-space: pre-wrap;">  </span>print "setting up";<br />
};</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="test-teardown" id="test-teardown"></a><a href="more#test-teardown-note">teardown</a></td>
<td><span style="color: gray"># in class TestFoo:</span><br />
sub teardown : Test(teardown) {<br />
<span style="white-space: pre-wrap;">  </span>print "tearing down";<br />
};</td>
<td></td>
<td></td>
</tr>
<tr>
<th colspan="4"><a name="debugging-profiling" id="debugging-profiling"></a><a href="more#debugging-profiling-note">debugging and profiling</a></th>
</tr>
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a name="check-syntax" id="check-syntax"></a><a href="more#check-syntax-note">check syntax</a></td>
<td>$ perl -c foo.pl</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="warning-flag" id="warning-flag"></a><a href="more#warning-flag-note">flags for stronger and strongest warnings</a></td>
<td>$ perl -w foo.pl<br />
$ perl -W foo.pl</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="lint" id="lint"></a><a href="more#lint-note">lint</a></td>
<td>$ perl MO=Lint foo.pl</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="debugger" id="debugger"></a><a href="more#debugger-note">debugger</a></td>
<td>$ perl -d foo.pl</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="debugger-cmd" id="debugger-cmd"></a><a href="more#debugger-cmd-note">debugger commands</a></td>
<td>h l n s b c T ?? ?? p q</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="benchmark-code" id="benchmark-code"></a><a href="more#benchmark-code-note">benchmark code</a></td>
<td>use Benchmark qw(:all);<br />
<br />
$t = timeit(1_000_000, '$i += 1;');<br />
print timestr($t);</td>
<td></td>
<td></td>
</tr>
<tr>
<td><a name="profile-code" id="profile-code"></a><a href="more#profile-code-note">profile code</a></td>
<td>$ perl -d:DProf foo.pl<br />
$ dprofpp</td>
<td></td>
<td></td>
</tr>
<tr>
<th></th>
<th><span style="color: #efefef"><span style="white-space: pre-wrap;">_________________________________________________________________</span></span></th>
<th><span style="color: #efefef"><span style="white-space: pre-wrap;">_________________________________________________________________</span></span></th>
<th><span style="color: #efefef"><span style="white-space: pre-wrap;">_________________________________________________________________</span></span></th>
</tr>
</table>
<p><a name="general-note" id="general-note"></a></p>
<h1 id="toc0"><span><a href="more#general">General</a></span></h1>
<p><a name="version-used-note" id="version-used-note"></a></p>
<h2 id="toc1"><span><a href="more#version-used">version used</a></span></h2>
<p>The version used for verifying the examples in this cheat sheet.</p>
<p><a name="show-version-note" id="show-version-note"></a></p>
<h2 id="toc2"><span><a href="more#show-version">show version</a></span></h2>
<p>How to get the version.</p>
<p><strong>perl:</strong></p>
<p>Also available in the predefined variable <tt>$]</tt>, or in a different format in <tt>$^V</tt> and <tt>$PERL_VERSION</tt>.</p>
<p><a name="implicit-prologue-note" id="implicit-prologue-note"></a></p>
<h2 id="toc3"><span><a href="more#implicit-prologue">implicit prologue</a></span></h2>
<p>Code which examples in the sheet assume to have already been executed.</p>
<p><strong>perl:</strong></p>
<p>We adopt the convention that if an example uses a variable without declaring it, it should be taken to have been previously declared with <tt>my</tt>.</p>
<p><a name="grammar-execution-note" id="grammar-execution-note"></a></p>
<h1 id="toc4"><span><a href="more#grammar-execution">Grammar and Execution</a></span></h1>
<p><a name="interpreter-note" id="interpreter-note"></a></p>
<h2 id="toc5"><span><a href="more#interpreter">interpreter</a></span></h2>
<p>The customary name of the interpreter and how to invoke it.</p>
<p><strong>unix:</strong></p>
<p>On Unix, scripts are executing by passing the file containing the script to the interpreter as an argument:</p>
<div class="code">
<pre>
<code>bash ~/configure.sh</code>
</pre></div>
<p>If the executable bit is set, the file can be run directly:</p>
<div class="code">
<pre>
<code>~/configure.sh</code>
</pre></div>
<p>To determine the name of the interpreter that will process the script, Unix will look for the presence of a shebang (#!) at the start of the file. If the pathname to a command follows the shebang, it will be used to interpret the script. If no shebang is present, the script will be interpreted with <em>sh</em>, which is <em>bash</em> on modern Unix systems.</p>
<p>Arguments that follow the command will be passed to interpreter as command line arguments.</p>
<p>If it is undesirable to specify the pathname of the interpreter, the env command can be used to search the PATH directories:</p>
<div class="code">
<pre>
<code>#!/usr/bin/env lua</code>
</pre></div>
<p><strong>groovy:</strong></p>
<p>Groovy does not in general have <tt>#</tt> style comments, but one can be used on the first line to create a shebang script:</p>
<div class="code">
<pre>
<code>#!/usr/bin/env groovy

println "hello world!"</code>
</pre></div>
<p><a name="repl-note" id="repl-note"></a></p>
<h2 id="toc6"><span><a href="more#repl">repl</a></span></h2>
<p>The customary name of the repl.</p>
<p><strong>perl:</strong></p>
<p>The Perl REPL <tt>perl -de 0</tt> does not save or display the result of an expression. <tt>perl -d</tt> is the Perl debugger and <tt>perl -e</tt> runs code provided on the command line.</p>
<p><tt>perl -de 0</tt> does not by default have readline, but it can be added:</p>
<div class="code">
<pre>
<code>$ cpan -i Term::ReadLine::Perl

  &lt;cpan output omitted&gt;

$ perl -de 0

  DB&lt;1&gt; use Term::ReadLine::Perl;

  DB&lt;2&gt; print 1 + 1;
2</code>
</pre></div>
<p><a name="cmd-line-program-note" id="cmd-line-program-note"></a></p>
<h2 id="toc7"><span><a href="more#cmd-line-program">command line program</a></span></h2>
<p>How to pass in a program to the interpreter on the command line.</p>
<p><a name="block-delimiters-note" id="block-delimiters-note"></a></p>
<h2 id="toc8"><span><a href="more#block-delimiters">block delimiters</a></span></h2>
<p>How blocks are delimited.</p>
<p><strong>perl:</strong></p>
<p>Curly brackets {} delimit blocks. They are also used for:</p>
<ul>
<li>hash literal syntax which returns a reference to the hash: <tt>$rh = { 'true' =&gt; 1, 'false' =&gt; 0 }</tt></li>
<li>hash value lookup: <tt>$h{'true'}, $rh-&gt;{'true'}</tt></li>
<li>variable name delimiter: <tt>$s = "hello"; print "${s}goodbye";</tt></li>
</ul>
<p><strong>lua:</strong></p>
<p>The <tt>function</tt> and <tt>if</tt> keywords open blocks which are terminated by <tt>end</tt> keywords. The <tt>repeat</tt> keyword opens a block which is terminated by <tt>until</tt>.</p>
<p><a name="stmt-separator-note" id="stmt-separator-note"></a></p>
<h2 id="toc9"><span><a href="more#stmt-separator">statement separator</a></span></h2>
<p>How the parser determines the end of a statement.</p>
<p><strong>perl:</strong></p>
<p>In a script statements are separated by semicolons and never by newlines. However, when using <tt>perl -de 0</tt> a newline terminates the statement.</p>
<p><a name="expr-stmt-note" id="expr-stmt-note"></a></p>
<h2 id="toc10"><span><a href="more#expr-stmt">are expressions statements</a></span></h2>
<p>Whether an expression can be used where a statement is expected.</p>
<p><a name="source-code-encoding-note" id="source-code-encoding-note"></a></p>
<h2 id="toc11"><span><a href="more#source-code-encoding">source code encoding</a></span></h2>
<p>How to identify the character encoding for a source code file.</p>
<p>Setting the source code encoding makes it possible to safely use non-ASCII characters in string literals and regular expression literals.</p>
<p><a name="eol-comment-note" id="eol-comment-note"></a></p>
<h2 id="toc12"><span><a href="more#eol-comment">end-of-line comment</a></span></h2>
<p>How to make the remainder of the line a comment.</p>
<p><a name="multiple-line-comment-note" id="multiple-line-comment-note"></a></p>
<h2 id="toc13"><span><a href="more#multiple-line-comment">multiple line comment</a></span></h2>
<p>How to comment out multiple lines.</p>
<p><strong>lua:</strong></p>
<p>The double bracket notation <tt>[[ ]]</tt> is the syntax for a multiline string literal.</p>
<p><a name="variables-expressions-note" id="variables-expressions-note"></a></p>
<h1 id="toc14"><span><a href="more#variables-expressions">Variables and Expressions</a></span></h1>
<p><a name="local-var-note" id="local-var-note"></a></p>
<h2 id="toc15"><span><a href="more#local-var">local variable</a></span></h2>
<p>How to declare a local variable.</p>
<p><strong>perl:</strong></p>
<p>Variables don't need to be declared unless <tt>use strict</tt> is in effect.</p>
<p>If not initialized, scalars are set to <tt>undef</tt>, arrays are set to an empty array, and hashes are set to an empty hash.</p>
<p>Perl can also declare variables with local. These replace the value of a global variable with the same name, if any, for the duration of the enclosing scope, after which the old value is restored.</p>
<p><a name="local-scope-region-note" id="local-scope-region-note"></a></p>
<h2 id="toc16"><span><a href="more#local-scope-region">regions which define local scope</a></span></h2>
<p>A list of regions which define a lexical scope for the local variables they contain.</p>
<p><strong>perl:</strong></p>
<p>A local variable can be defined outside of any function definition or anonymous block, in which case the scope of the variable is the file containing the source code.</p>
<p>When a region which defines a scope is nested inside another, then the inner region has read and write access to local variables defined in the outer region.</p>
<p>Note that the blocks associated with the keywords <tt>if</tt>, <tt>unless</tt>, <tt>while</tt>, <tt>until</tt>, <tt>for</tt>, and <tt>foreach</tt> are anonymous blocks, and thus any <tt>my</tt> declarations in them create variables local to the block.</p>
<p><a name="global-var-note" id="global-var-note"></a></p>
<h2 id="toc17"><span><a href="more#global-var">global variable</a></span></h2>
<p>How to declare and access a global variable.</p>
<p><strong>perl:</strong></p>
<p>Undeclared variables, which are permitted unless <tt>use strict</tt> is in effect, are global. If <tt>use strict</tt> is in effect, a global can be declared at the top level of a package (i.e. outside any blocks or functions) with the our keyword. A variable declared with <tt>my</tt> inside a function will hide a global with the same name, if there is one.</p>
<p><a name="const-note" id="const-note"></a></p>
<h2 id="toc18"><span><a href="more#const">constant</a></span></h2>
<p>How to declare a constant.</p>
<p><a name="assignment-note" id="assignment-note"></a></p>
<h2 id="toc19"><span><a href="more#assignment">assignment</a></span></h2>
<p>How to assign a value to a variable.</p>
<p><strong>perl:</strong></p>
<p>Assignment operators have right precedence and evaluate to the right argument, so assignments can be chained:</p>
<div class="code">
<pre>
<code>$a = $b = 3;</code>
</pre></div>
<p><a name="parallel-assignment-note" id="parallel-assignment-note"></a></p>
<h2 id="toc20"><span><a href="more#parallel-assignment">parallel assignment</a></span></h2>
<p>Whether parallel assignment is supported, and if so how to do it.</p>
<p><a name="swap-note" id="swap-note"></a></p>
<h2 id="toc21"><span><a href="more#swap">swap</a></span></h2>
<p>How to swap the values in two variables.</p>
<p><a name="compound-assignment-note" id="compound-assignment-note"></a></p>
<h2 id="toc22"><span><a href="more#compound-assignment">compound assignment</a></span></h2>
<p>Compound assignment operators mutate a variable, setting it to the value of an operation which takes the previous value of the variable as an argument.</p>
<p><a name="incr-decr-note" id="incr-decr-note"></a></p>
<h2 id="toc23"><span><a href="more#incr-decr">increment and decrement</a></span></h2>
<p>The C-style increment and decrement operators can be used to increment or decrement values. They return values and thus can be used in expressions. The prefix versions return the value in the variable after mutation, and the postfix version return the value before mutation.</p>
<p><strong>perl:</strong></p>
<p>The increment and decrement operators also work on strings. There are postfix versions of these operators which evaluate to the value before mutation:</p>
<div class="code">
<pre>
<code>$x = 1;
$x++;
$x--;</code>
</pre></div>
<p><a name="null-note" id="null-note"></a></p>
<h2 id="toc24"><span><a href="more#null">null</a></span></h2>
<p>The null literal.</p>
<p><a name="null-test-note" id="null-test-note"></a></p>
<h2 id="toc25"><span><a href="more#null-test">null test</a></span></h2>
<p>How to test if a value is null.</p>
<p><strong>perl:</strong></p>
<p><tt>$v == undef</tt> does not imply that <tt>$v</tt> is <tt>undef</tt>. Any comparison between <tt>undef</tt> and a falsehood will return true. The following comparisons are true:</p>
<div class="code">
<pre>
<code>$v = undef;
if ($v == undef) { print "true"; }

$v = 0;
if ($v == undef) { print "sadly true"; }

$v = '';
if ($v == undef) { print "sadly true"; }</code>
</pre></div>
<p><a name="undef-var-note" id="undef-var-note"></a></p>
<h2 id="toc26"><span><a href="more#undef-var">undefined variable access</a></span></h2>
<p>What happens when the value in an undefined variable is accessed.</p>
<p><strong>perl:</strong></p>
<p>Perl does not distinguish between unset variables and variables that have been set to <tt>undef</tt>. In Perl, calling <tt>defined($a)</tt> does not result in a error if <tt>$a</tt> is undefined, even with the <tt>strict</tt> pragma.</p>
<p><strong>lua:</strong></p>
<p>There is no distinction between a variable being defined and a variable having a nil value. Assigning nil to a variable frees it.</p>
<p><a name="conditional-expr-note" id="conditional-expr-note"></a></p>
<h2 id="toc27"><span><a href="more#conditional-expr">conditional expression</a></span></h2>
<p>How to write a conditional expression.</p>
<p><strong>lua:</strong></p>
<p><a href="http://lua-users.org/wiki/TernaryOperator">notes on Lua and the ternary operator</a></p>
<p><a name="arithmetic-logic-note" id="arithmetic-logic-note"></a></p>
<h1 id="toc28"><span><a href="more#arithmetic-logic">Arithmetic and Logic</a></span></h1>
<p><a name="true-false-note" id="true-false-note"></a></p>
<h2 id="toc29"><span><a href="more#true-false">true and false</a></span></h2>
<p>The literals for true and false.</p>
<p><a name="falsehoods-note" id="falsehoods-note"></a></p>
<h2 id="toc30"><span><a href="more#falsehoods">falsehoods</a></span></h2>
<p>Values which are false in conditional expressions.</p>
<p><a name="logical-op-note" id="logical-op-note"></a></p>
<h2 id="toc31"><span><a href="more#logical-op">logical operators</a></span></h2>
<p>Logical and, or, and not.</p>
<p><strong>perl:</strong></p>
<p>&amp;&amp; and || have higher precedence than assignment, compound assignment, and the ternary operator (?:), which have higher precedence than and and or.</p>
<p><a name="relational-expr-note" id="relational-expr-note"></a></p>
<h2 id="toc32"><span><a href="more#relational-expr">relational expressions</a></span></h2>
<p>How to write a relational expression.</p>
<p><a name="relational-op-note" id="relational-op-note"></a></p>
<h2 id="toc33"><span><a href="more#relational-op">relational operators</a></span></h2>
<p>The available relational operators.</p>
<p><strong>perl:</strong></p>
<p>The operators: == != &gt; &lt; &gt;= &lt;= convert strings to numbers before performing a comparison. Many string evaluate as zero in a numeric context and are equal according to the == operator. To perform a lexicographic string comparison, use: <em>eq</em>, <em>ne</em>, <em>gt</em>, <em>lt</em>, <em>ge</em>, <em>le</em>.</p>
<p><a name="min-max-note" id="min-max-note"></a></p>
<h2 id="toc34"><span><a href="more#min-max">min and max</a></span></h2>
<p>How to find the min and max value in mix of values or variables.</p>
<p><a name="three-val-comparison-note" id="three-val-comparison-note"></a></p>
<h2 id="toc35"><span><a href="more#three-val-comparison">three value comparison</a></span></h2>
<p>Binary comparison operators which return -1, 0, or 1 depending upon whether the left argument is less than, equal to, or greater than the right argument.</p>
<p>The <tt>&lt;=&gt;</tt> symbol is called the spaceship operator.</p>
<p><a name="arith-expr-note" id="arith-expr-note"></a></p>
<h2 id="toc36"><span><a href="more#arith-expr">arithmetic expression</a></span></h2>
<p>How to evaluate an arithmetic expression.</p>
<p><a name="arith-op-note" id="arith-op-note"></a></p>
<h2 id="toc37"><span><a href="more#arith-op">arithmetic operators</a></span></h2>
<p>The binary arithmetic operators.</p>
<p>The operators for addition, subtraction, multiplication, float division, integer division, modulus, and exponentiation. Some languages provide a function <em>pow</em> instead of an operator for exponentiation.</p>
<p><a name="int-div-note" id="int-div-note"></a></p>
<h2 id="toc38"><span><a href="more#int-div">integer division</a></span></h2>
<p>How to perform integer division.</p>
<p><strong>perl:</strong></p>
<p>The <tt>integer</tt> pragma makes all arithmetic operations integer operations. Floating point numbers are truncated before they are used. Hence integer division could be performed with:</p>
<div class="code">
<pre>
<code>use integer;
my $a = 7 / 3;
no integer;</code>
</pre></div>
<p><strong>lua:</strong></p>
<p>All Lua numbers are floating point.</p>
<p><a name="int-div-zero-note" id="int-div-zero-note"></a></p>
<h2 id="toc39"><span><a href="more#int-div-zero">integer division by zero</a></span></h2>
<p>What happens when a float is divided by zero.</p>
<p><strong>lua</strong></p>
<p>As already noted there are no literals for <tt>inf</tt> and <tt>nan</tt>. Once could assign the correct values<br />
to variables with the following code</p>
<div class="code">
<pre>
<code>inf = 1 / 0
nan = 0 / 0</code>
</pre></div>
<p><tt>inf</tt> can be compared to itself, but <tt>nan</tt> cannot. In other words:</p>
<div class="code">
<pre>
<code># this prints 'true'
=(1 / 0) == (1 / 0)
# this prints 'false'
=(0 / 0) == (0 / 0)</code>
</pre></div>
<p><a name="float-div-note" id="float-div-note"></a></p>
<h2 id="toc40"><span><a href="more#float-div">float division</a></span></h2>
<p>How to perform floating point division, even if the operands might be integers.</p>
<p><a name="float-div-zero-note" id="float-div-zero-note"></a></p>
<h2 id="toc41"><span><a href="more#float-div-zero">float division by zero</a></span></h2>
<p>The result of dividing a float by zero.</p>
<p><a name="power-note" id="power-note"></a></p>
<h2 id="toc42"><span><a href="more#power">power</a></span></h2>
<p>How to compute exponentiation.</p>
<p>The examples calculate 2 to the 32 which is the number of distinct values that can be stored in 32 bits.</p>
<p><a name="sqrt-note" id="sqrt-note"></a></p>
<h2 id="toc43"><span><a href="more#sqrt">sqrt</a></span></h2>
<p>How to get the square root of a number.</p>
<p><a name="sqrt-negative-one-note" id="sqrt-negative-one-note"></a></p>
<h2 id="toc44"><span><a href="more#sqrt-negative-one">sqrt -1</a></span></h2>
<p>The result of taking the square root of -1.</p>
<p><a name="transcendental-func-note" id="transcendental-func-note"></a></p>
<h2 id="toc45"><span><a href="more#transcendental-func">transcendental functions</a></span></h2>
<p>Functions for computing the natural exponent, natural logarithm, sine, cosine, tangent, arcsine, arccosine, arctangent, and <tt>atan2</tt>.</p>
<p>The trigonometric functions are all in radians. <tt>atan2</tt> takes two arguments which are the x and y co-ordinates of a vector in the Cartesian plane. It returns<br />
the angle to the positive x-axis made by the vector.</p>
<p><a name="transcendental-const-note" id="transcendental-const-note"></a></p>
<h2 id="toc46"><span><a href="more#transcendental-const">transcendental constants</a></span></h2>
<p>Approximate values for <em>π</em> and <em>e</em>.</p>
<p><a name="float-truncation-note" id="float-truncation-note"></a></p>
<h2 id="toc47"><span><a href="more#float-truncation">float truncation</a></span></h2>
<p>Ways to convert a float to a nearby integer: towards zero; to the nearest integer; towards positive infinity; towards negative infinity.</p>
<p><strong>perl:</strong></p>
<p>The CPAN module <tt>Number::Format</tt> provides a <tt>round</tt> function. The 2nd argument specifies the number of digits to keep to the right of the radix. The default is 2.</p>
<div class="code">
<pre>
<code>use Number::Format 'round';

round(3.14, 0);</code>
</pre></div>
<p><a name="absolute-val-note" id="absolute-val-note"></a></p>
<h2 id="toc48"><span><a href="more#absolute-val">absolute value</a></span></h2>
<p>How to get the absolute value of a number.</p>
<p><a name="int-overflow-note" id="int-overflow-note"></a></p>
<h2 id="toc49"><span><a href="more#int-overflow">integer overflow</a></span></h2>
<p>What happens when an operation yields an integer larger than the largest representable value.</p>
<p><a name="float-overflow-note" id="float-overflow-note"></a></p>
<h2 id="toc50"><span><a href="more#float-overflow">float overflow</a></span></h2>
<p>What happens when an operation yields a float larger than the largest representable value.</p>
<p><a name="rational-construction-note" id="rational-construction-note"></a></p>
<h2 id="toc51"><span><a href="more#rational-construction">rational construction</a></span></h2>
<p>How to construct a rational number.</p>
<p><a name="rational-decomposition-note" id="rational-decomposition-note"></a></p>
<h2 id="toc52"><span><a href="more#rational-decomposition">rational decomposition</a></span></h2>
<p>How to decompose a rational number into a numerator and a denominator.</p>
<p><a name="complex-construction-note" id="complex-construction-note"></a></p>
<h2 id="toc53"><span><a href="more#complex-construction">complex construction</a></span></h2>
<p>How to construct a complex number.</p>
<p><a name="complex-decomposition-note" id="complex-decomposition-note"></a></p>
<h2 id="toc54"><span><a href="more#complex-decomposition">complex decomposition</a></span></h2>
<p>How to decompose a complex number into its real and imaginary part; how to get the polar decomposition of a complex number; how to get the complex conjugate.</p>
<p><a name="random-num-note" id="random-num-note"></a></p>
<h2 id="toc55"><span><a href="more#random-num">random number</a></span></h2>
<p>The examples show how to generate a uniform random integer in the range from 0 to 99, inclusive; how to generate a uniform float in the range 0.0 to 1.0; how to generate a float from a standard normal distribution</p>
<p><a name="random-seed-note" id="random-seed-note"></a></p>
<h2 id="toc56"><span><a href="more#random-seed">random seed</a></span></h2>
<p>How to set the seed for the random number generator.</p>
<p>Setting the seed to a fixed number can be used for repeatable results.</p>
<p><a name="bit-op-note" id="bit-op-note"></a></p>
<h2 id="toc57"><span><a href="more#bit-op">bit operators</a></span></h2>
<p>The available bit operators.</p>
<p><a name="binary-oct-hex-literals-note" id="binary-oct-hex-literals-note"></a></p>
<h2 id="toc58"><span><a href="more#binary-oct-hex-literals">binary, octal, and hex literals</a></span></h2>
<p>Binary, octal, and hex integer literals</p>
<p><a name="radix-note" id="radix-note"></a></p>
<h2 id="toc59"><span><a href="more#radix">radix</a></span></h2>
<p>How to convert integers to strings of digits of a given base. How to convert such strings into integers.</p>
<p><strong>perl:</strong></p>
<p>Perl has the functions <tt>oct</tt> and <tt>hex</tt> which convert strings encoded in octal and hex and return the corresponding integer. The <tt>oct</tt> function will handle binary or hex encoded strings if they have "0b" or "0x" prefixes.</p>
<div class="code">
<pre>
<code>oct("60")
oct("060")
oct("0b101010")
oct("0x2a")

hex("2a")
hex("0x2a")</code>
</pre></div>
<p><a name="strings-note" id="strings-note"></a></p>
<h1 id="toc60"><span><a href="more#strings">Strings</a></span></h1>
<p><a name="str-literal-note" id="str-literal-note"></a></p>
<h2 id="toc61"><span><a href="more#str-literal">string literal</a></span></h2>
<p>The syntax for a string literal.</p>
<p><strong>perl:</strong></p>
<p>When <tt>use strict</tt> is not in effect bareword strings are permitted.</p>
<p>Barewords are strings without quote delimiters. They are a feature of shells. Barewords cannot contain whitespace or any other character used by the tokenizer to distinguish words.</p>
<p>Before Perl 5 subroutines were invoked with an ampersand prefix &amp; or the older <tt>do</tt> keyword. With Perl 5 neither is required, but this made it impossible to distinguish a bareword string from a subroutine without knowing all the subroutines which are in scope.</p>
<p>The following code illustrates the bareword ambiguity:</p>
<div class="code">
<pre>
<code>no strict;

print rich . "\n";  # prints "rich"; rich is a bareword string

sub rich { return "poor" }

print rich . "\n";  # prints "poor"; rich is now a subroutine</code>
</pre></div>
<p>Perl allows custom delimiters to be used for single and double quoted strings. These can be used to avoid backslash escaping. If the left delimiter is (, [, or { the right delimiter must be ), ], or }, respectively.</p>
<div class="code">
<pre>
<code>my $s1 = q(lorem ipsum);
my $s2 = qq($s1 dolor sit amet);</code>
</pre></div>
<p><a name="str-literal-newline-note" id="str-literal-newline-note"></a></p>
<h2 id="toc62"><span><a href="more#str-literal-newline">newline in literal</a></span></h2>
<p>Are newlines permitted in a string literal?</p>
<p><strong>lua:</strong></p>
<p>One can avoid backslashes by using the double bracket string notation. The following are equivalent:</p>
<div class="code">
<pre>
<code>s = "one\
two\
three"

s = [[one
two
three]]</code>
</pre></div>
<p><a name="char-esc-note" id="char-esc-note"></a></p>
<h2 id="toc63"><span><a href="more#char-esc">literal escapes</a></span></h2>
<p>Backslash escape sequences that can be used in a string literal.</p>
<p><strong>perl:</strong></p>
<p>In addition to the character escapes, Perl has the following translation escapes:</p>
<table class="wiki-content-table">
<tr>
<td>\u</td>
<td>make next character uppercase</td>
</tr>
<tr>
<td>\l</td>
<td>make next character lowercase</td>
</tr>
<tr>
<td>\U</td>
<td>make following characters uppercase</td>
</tr>
<tr>
<td>\L</td>
<td>make following characters lowercase</td>
</tr>
<tr>
<td>\Q</td>
<td>backslash escape following nonalphanumeric characters</td>
</tr>
<tr>
<td>\E</td>
<td>end \U, \L, or \Q section</td>
</tr>
</table>
<p>When <tt>use charnames</tt> is in effect the \N escape sequence is available:</p>
<div class="code">
<pre>
<code>binmode(STDOUT, ':utf8');

use charnames ':full';

print "lambda: \N{GREEK SMALL LETTER LAMDA}\n";

use charnames ':short';

print "lambda: \N{greek:lamda}\n";

use charnames qw(greek);

print "lambda: \N{lamda}\n";</code>
</pre></div>
<p><a name="here-doc-note" id="here-doc-note"></a></p>
<h2 id="toc64"><span><a href="more#here-doc">here document</a></span></h2>
<p>Here documents are strings terminated by a custom identifier. They perform variable substitution and honor the same backslash escapes as double quoted strings.</p>
<p><strong>perl:</strong></p>
<p>Put the custom identifier in single quotes to prevent variable interpolation and backslash escape interpretation:</p>
<div class="code">
<pre>
<code>s = &lt;&lt;'EOF';
Perl code uses variables with dollar
signs, e.g. $var
EOF</code>
</pre></div>
<p><a name="var-interpolation-note" id="var-interpolation-note"></a></p>
<h2 id="toc65"><span><a href="more#var-interpolation">variable interpolation</a></span></h2>
<p>The syntax for interpolating variables into a string literal.</p>
<p><a name="expr-interpolation-note" id="expr-interpolation-note"></a></p>
<h2 id="toc66"><span><a href="more#expr-interpolation">expression interpolation</a></span></h2>
<p>Interpolating the result of evaluating an expression in a string literal.</p>
<p><a name="str-concat-note" id="str-concat-note"></a></p>
<h2 id="toc67"><span><a href="more#str-concat">concatenate</a></span></h2>
<p>The string concatenation operator.</p>
<p><a name="str-replicate-note" id="str-replicate-note"></a></p>
<h2 id="toc68"><span><a href="more#str-replicate">replicate</a></span></h2>
<p>The string replication operator.</p>
<p><a name="split-note" id="split-note"></a></p>
<h2 id="toc69"><span><a href="more#split">split</a></span></h2>
<p><strong>lua:</strong></p>
<p><a href="http://lua-users.org/wiki/SplitJoin">how to split a string in Lua</a></p>
<p><a name="join-note" id="join-note"></a></p>
<h2 id="toc70"><span><a href="more#join">join</a></span></h2>
<p>How to concatenate the elements of an array into a string with a separator.</p>
<p><a name="sprintf-note" id="sprintf-note"></a></p>
<h2 id="toc71"><span><a href="more#sprintf">sprintf</a></span></h2>
<p>How to create a string using a printf style format.</p>
<p><a name="case-note" id="case-note"></a></p>
<h2 id="toc72"><span><a href="more#case">case manipulation</a></span></h2>
<p><a name="trim-note" id="trim-note"></a></p>
<h2 id="toc73"><span><a href="more#trim">trim</a></span></h2>
<p>How to remove whitespace from the ends of a string.</p>
<p><strong>perl:</strong></p>
<p>An example of how to trim a string without installing a library:</p>
<div class="code">
<pre>
<code>$s = " lorem ";
$s =~ s/^\s*(.*)\s*$/\1/;</code>
</pre></div>
<p>The return value of the <tt>=~</tt> operator is boolean, indicating whether a match occurred. Also the left hand side of the <tt>=~</tt> operator must be a scalar variable that can be modified. Using the <tt>=~</tt> operator is necessarily imperative, unlike the <tt>Text::Trim</tt> functions which can be used in expressions.</p>
<p><a name="pad-note" id="pad-note"></a></p>
<h2 id="toc74"><span><a href="more#pad">pad</a></span></h2>
<p>How to pad a string to a given length on the right; how to pad on the left; how to center a string inside a larger string of a given length.</p>
<p><strong>groovy</strong></p>
<p>Provide a second argument to set the pad character:</p>
<div class="code">
<pre>
<code>"lorem".padRight(10, '_')
"lorem".padLeft(10, '_')
"lorem.center(10, '_')</code>
</pre></div>
<p><a name="str-to-num-note" id="str-to-num-note"></a></p>
<h2 id="toc75"><span><a href="more#str-to-num">string to number</a></span></h2>
<p>How to convert a string to a number.</p>
<p><strong>perl:</strong></p>
<p>Perl converts a scalar to the desired type automatically and does not raise an error if the string contains non-numeric data. If the start of the string is not numeric, the string evaluates to zero in a numeric context.</p>
<p><strong>lua:</strong></p>
<p>Arithmetic operators will attempt to convert strings to numbers; if the string contains non-numeric data an error results. Note that relational operators do not perform conversion. Thus the following expression is false:</p>
<div class="code">
<pre>
<code> 0 == '0'</code>
</pre></div>
<p><a name="num-to-str-note" id="num-to-str-note"></a></p>
<h2 id="toc76"><span><a href="more#num-to-str">number to string</a></span></h2>
<p>How to convert a number to a string.</p>
<p><strong>lua:</strong></p>
<p><em>print</em> and the .. operator will convert all types to strings.</p>
<div class="code">
<pre>
<code>(8).toString()
x = 7
x.toString()</code>
</pre></div>
<br />
<a name="str-length-note" id="str-length-note"></a>
<h2 id="toc77"><span><a href="more#str-length">length</a></span></h2>
<p>How to get the number of characters in a string.</p>
<p><a name="index-substr-note" id="index-substr-note"></a></p>
<h2 id="toc78"><span><a href="more#index-substr">index substring</a></span></h2>
<p>How to get the index of the leftmost occurrence of a substring.</p>
<p><a name="extract-substr-note" id="extract-substr-note"></a></p>
<h2 id="toc79"><span><a href="more#extract-substr">extract substring</a></span></h2>
<p>How to extract a substring.</p>
<p><a name="chr-ord-note" id="chr-ord-note"></a></p>
<h2 id="toc80"><span><a href="more#chr-ord">chr and ord</a></span></h2>
<p>converting characters to ASCII codes and back</p>
<p><a name="regexes-note" id="regexes-note"></a></p>
<h1 id="toc81"><span><a href="more#regexes">Regular Expressions</a></span></h1>
<ul>
<li><a href="http://perldoc.perl.org/perlre.html">perlre</a> and <a href="http://perldoc.perl.org/perlreref.html">perlreref</a></li>
</ul>
<p><a name="regex-literal-note" id="regex-literal-note"></a></p>
<h2 id="toc82"><span><a href="more#regex-literal">literal, custom delimited literal</a></span></h2>
<p>The literal for a regular expression; the literal for a regular expression with a custom delimiter.</p>
<p><a name="char-class-abbrev-note" id="char-class-abbrev-note"></a></p>
<h2 id="toc83"><span><a href="more#char-class-abbrev">character class abbreviations and anchors</a></span></h2>
<p>The supported character class abbreviations and anchors</p>
<table class="wiki-content-table">
<tr>
<th>abbrev</th>
<th>description</th>
</tr>
<tr>
<td>.</td>
<td>any character; doesn't match newline when -linestop in effect</td>
</tr>
<tr>
<td>^</td>
<td>beginning of string; beginning of line when -lineanchor in effect</td>
</tr>
<tr>
<td>$</td>
<td>end of string; end of line when -lineanchor in effect</td>
</tr>
<tr>
<td>\A</td>
<td>beginning of string</td>
</tr>
<tr>
<td>%a</td>
<td>letter</td>
</tr>
<tr>
<td>\b, \y</td>
<td>word boundary</td>
</tr>
<tr>
<td>\B, \Y</td>
<td>not a word boundary</td>
</tr>
<tr>
<td>%c</td>
<td>control character</td>
</tr>
<tr>
<td>\d, %d</td>
<td>digit [0-9]</td>
</tr>
<tr>
<td>\D</td>
<td>not a digit [^0-9]</td>
</tr>
<tr>
<td>\h</td>
<td>horizontal whitespace character [ \t]</td>
</tr>
<tr>
<td>\H</td>
<td>not a horizontal whitespace character [^ \t]</td>
</tr>
<tr>
<td>%l</td>
<td>lowercase letter</td>
</tr>
<tr>
<td>\m</td>
<td>beginning of a word</td>
</tr>
<tr>
<td>\M</td>
<td>end of a word</td>
</tr>
<tr>
<td>%p</td>
<td>punctuation character</td>
</tr>
<tr>
<td>\s</td>
<td>white space</td>
</tr>
<tr>
<td>\S</td>
<td>not white space</td>
</tr>
<tr>
<td>%u</td>
<td>uppercase letter</td>
</tr>
<tr>
<td>\v</td>
<td>vertical whitespace character [\r\n\f]</td>
</tr>
<tr>
<td>\V</td>
<td>not a vertical whitespace character [^\r\n\f]</td>
</tr>
<tr>
<td>\w, %w</td>
<td>alphanumeric character. \w also matches underscore</td>
</tr>
<tr>
<td>\W</td>
<td>not a word character</td>
</tr>
<tr>
<td>\Z</td>
<td>end of string</td>
</tr>
<tr>
<td>%z</td>
<td>the null character (ASCII zero)</td>
</tr>
</table>
<p><a name="regex-anchors-note" id="regex-anchors-note"></a></p>
<h2 id="toc84"><span><a href="more#regex-anchors">anchors</a></span></h2>
<p>The supported anchors.</p>
<p><a name="regex-match-note" id="regex-match-note"></a></p>
<h2 id="toc85"><span><a href="more#regex-match">match test</a></span></h2>
<p>How to test whether a regular expression matches a string.</p>
<p><strong>groovy</strong></p>
<p>The <tt>=~</tt> operator succeeds if the regex matches part of the string. The <tt>==~</tt> succeeds only if the regular expression matches the entire string:</p>
<div class="code">
<pre>
<code>s = "it's 1999"

// true:
s =~ /1999/

// false:
s ==~ /1999/</code>
</pre></div>
<p><a name="case-insensitive-regex-note" id="case-insensitive-regex-note"></a></p>
<h2 id="toc86"><span><a href="more#case-insensitive-regex">case insensitive match test</a></span></h2>
<p>How to test whether a regular expression matches a string, ignoring case.</p>
<p><a name="regex-modifiers-note" id="regex-modifiers-note"></a></p>
<h2 id="toc87"><span><a href="more#regex-modifiers">modifiers</a></span></h2>
<p>Available flags for modifying regular expression behavior.</p>
<p><a name="subst-note" id="subst-note"></a></p>
<h2 id="toc88"><span><a href="more#subst">substitution</a></span></h2>
<p>How to replace all occurrences of a pattern in a string with a substitution.</p>
<p><strong>perl:</strong></p>
<p>The <tt>=~</tt> operator performs the substitution in place on the string and returns the number of substitutions performed.</p>
<p>The <tt>g</tt> modifiers specifies that all occurrences should be replaced. If omitted, only the first occurrence is replaced.</p>
<p><strong>lua:</strong></p>
<p>To specify the maximum number of pattern occurrences to be replaced, provide a fourth argument:</p>
<div class="code">
<pre>
<code>s = "do re mi mi mi"
s = string.gsub(s, "mi", "ma", 1)</code>
</pre></div>
<p><a name="match-prematch-postmatch-note" id="match-prematch-postmatch-note"></a></p>
<h2 id="toc89"><span><a href="more#match-prematch-postmatch">match, prematch, postmatch</a></span></h2>
<p>How to get the substring that matched the regular expression, as well as the part of the string before and after the matching substring.</p>
<p><strong>perl:</strong></p>
<p>The special variables <tt>$&amp;</tt>, <tt>$<span style="white-space: pre-wrap;">`</span></tt>, and <tt>$'</tt> also contain the match, prematch, and postmatch.</p>
<p><a name="group-capture-note" id="group-capture-note"></a></p>
<h2 id="toc90"><span><a href="more#group-capture">group capture</a></span></h2>
<p>How to get the substrings which matched a parenthesized portion of a regular expression.</p>
<p><a name="named-group-capture-note" id="named-group-capture-note"></a></p>
<h2 id="toc91"><span><a href="more#named-group-capture">named group capture</a></span></h2>
<p>How to get the substrings which matched the parenthesized parts of a regular expression and put them into a dictionary.</p>
<p>For reference, we call the <tt>(?P&lt;foo&gt;<span style="white-space: pre-wrap;">...</span>)</tt> notation <em>Python-style</em> and the <tt>(?&lt;foo&gt;<span style="white-space: pre-wrap;">...</span>)</tt> notation <em>Perl-style</em>.</p>
<p><strong>perl:</strong></p>
<p>Perl 5.10 added support for both Python-style and Perl-style named groups.</p>
<p><a name="backreference-note" id="backreference-note"></a></p>
<h2 id="toc92"><span><a href="more#backreference">backreference</a></span></h2>
<p>How to use backreferences in a regex; how to use backreferences in the replacement string of substitution.</p>
<p>Perl uses and exposes the <tt>tm</tt> struct of the standard library. The first nine values of the struct (up to the member <tt>tm_isdst</tt>) are put into an array.</p>
<p><a name="dates-time-note" id="dates-time-note"></a></p>
<h1 id="toc93"><span><a href="more#dates-time">Date and Time</a></span></h1>
<p><a name="date-time-type-note" id="date-time-type-note"></a></p>
<h2 id="toc94"><span><a href="more#date-time-type">date/time type</a></span></h2>
<p>The data type used to hold a combined date and time.</p>
<p><strong>perl</strong></p>
<p>Built in Perl functions work with either (1) scalars containing the Unix epoch as an integer or (2) arrays containing the first nine values of the standard C library tm struct. When <tt>use Time::Piece</tt> is in effect functions which work with tm arrays are replaced with variant that work with the <tt>Time::Piece</tt> wrapper.</p>
<p>The modules <tt>Time::Local</tt> and <tt>Date::Parse</tt> can create scalars containing the Unix epoch.</p>
<p>CPAN provides the <tt>DateTime</tt> module which provides objects with functionality comparable to the DateTime objects of PHP and Python.</p>
<p><a name="current-date-time-note" id="current-date-time-note"></a></p>
<h2 id="toc95"><span><a href="more#current-date-time">current date/time</a></span></h2>
<p>How to get the current time.</p>
<p><a name="unix-epoch-note" id="unix-epoch-note"></a></p>
<h2 id="toc96"><span><a href="more#unix-epoch">to unix epoch, from unix epoch</a></span></h2>
<p>How to convert a date/time object to the Unix epoch; how to convert a date/time object from the Unix epoch.</p>
<p>The Unix epoch is the number of seconds since January 1, 1970 UTC. In the case of Lua, the native date/time object is the Unix epoch, so no conversion is needed.</p>
<p><a name="current-unix-epoch-note" id="current-unix-epoch-note"></a></p>
<h2 id="toc97"><span><a href="more#current-unix-epoch">current unix epoch</a></span></h2>
<p><a name="strftime-note" id="strftime-note"></a></p>
<h2 id="toc98"><span><a href="more#strftime">strftime</a></span></h2>
<p>How to use a strftime style format string to convert a date/time object to a string representation.</p>
<p><tt>strftime</tt> is from the C standard library. The Unix <tt>date</tt> command uses the same style of format.</p>
<p><a name="strptime-note" id="strptime-note"></a></p>
<h2 id="toc99"><span><a href="more#strptime">strptime</a></span></h2>
<p>How to parse a string into a date/time object using a <tt>strftime</tt> style format string. <tt>strptime</tt> is from the C standard library.</p>
<p><a name="parse-date-note" id="parse-date-note"></a></p>
<h2 id="toc100"><span><a href="more#parse-date">parse date w/o format</a></span></h2>
<p>How to parse a string into a date/time object without using a format string.</p>
<p><a name="get-date-parts-note" id="get-date-parts-note"></a></p>
<h2 id="toc101"><span><a href="more#get-date-parts">get date parts</a></span></h2>
<p>How to get the year as a four digit integer; how to get the month as an integer from 1 to 12; how to get the day of the month as an integer from 1 to 31.</p>
<p><a name="get-time-parts-note" id="get-time-parts-note"></a></p>
<h2 id="toc102"><span><a href="more#get-time-parts">get time parts</a></span></h2>
<p>How to get the hour as an integer from 0 to 23; how to get the minute as an integer from 0 to 59; how to get the second as an integer from 0 to 59.</p>
<p><a name="date-from-parts-note" id="date-from-parts-note"></a></p>
<h2 id="toc103"><span><a href="more#date-from-parts">build date/time from parts</a></span></h2>
<p>How to assemble a date/time object from the 4 digit year, month (1-12), day (1-31), hour (0-23), minute (0-59), and second (0-59).</p>
<p><a name="date-subtraction-note" id="date-subtraction-note"></a></p>
<h2 id="toc104"><span><a href="more#date-subtraction">result of date subtraction</a></span></h2>
<p><a name="add-time-duration-note" id="add-time-duration-note"></a></p>
<h2 id="toc105"><span><a href="more#add-time-duration">add time duration</a></span></h2>
<p><a name="local-tmz-note" id="local-tmz-note"></a></p>
<h2 id="toc106"><span><a href="more#local-tmz">local timezone</a></span></h2>
<p><a name="tmz-offset-note" id="tmz-offset-note"></a></p>
<h2 id="toc107"><span><a href="more#tmz-offset">timezone name, offset from UTC, is daylight savings?</a></span></h2>
<p>How to get time zone information: the name of the timezone, the offset in hours from UTC, and whether the timezone is currently in daylight savings.</p>
<p>Timezones are often identified by <a href="http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations">three or four letter abbreviations</a>. As can be seen from the list, many of the abbreviations do not uniquely identify a timezone. Furthermore many of the timezones have been altered in the past. The <a href="http://en.wikipedia.org/wiki/Tz_database">Olson database</a> (aka Tz database) decomposes the world into zones in which the local clocks have all been set to the same time since 1970 and it gives these zones unique names.</p>
<p><strong>perl:</strong></p>
<p>It is not necessary to create a DateTime object to get the local timezone offset:</p>
<div class="code">
<pre>
<code>use Time::Piece;

$t = localtime(time);
$offset_hrs = $t-&gt;tzoffset / 3600;</code>
</pre></div>
<p><a name="microseconds-note" id="microseconds-note"></a></p>
<h2 id="toc108"><span><a href="more#microseconds">microseconds</a></span></h2>
<p><a name="sleep-note" id="sleep-note"></a></p>
<h2 id="toc109"><span><a href="more#sleep">sleep</a></span></h2>
<p>How to sleep for half a second.</p>
<p><strong>perl:</strong></p>
<p>The Perl standard library includes a version of <tt>sleep</tt> which supports fractional seconds:</p>
<div class="code">
<pre>
<code>use Time::HiRes qw(sleep);

sleep 0.5;</code>
</pre></div>
<p><a name="timeout-note" id="timeout-note"></a></p>
<h2 id="toc110"><span><a href="more#timeout">timeout</a></span></h2>
<p><a name="arrays-note" id="arrays-note"></a></p>
<h1 id="toc111"><span><a href="more#arrays">Arrays</a></span></h1>
<p>The names given by the languages for their basic container types:</p>
<table class="wiki-content-table">
<tr>
<th></th>
<th>perl</th>
<th>lua</th>
<th>groovy</th>
</tr>
<tr>
<td><a href="more#arrays">array</a></td>
<td>array, list</td>
<td>table</td>
<td>java.util.ArrayList</td>
</tr>
<tr>
<td><a href="more#dict">dictionary</a></td>
<td>hash</td>
<td>table</td>
<td>java.util.LinkedHashMap</td>
</tr>
</table>
<p><strong>perl:</strong></p>
<p>Arrays are a data type. Lists are a context.</p>
<p><strong>lua:</strong></p>
<p>Note that Lua uses the same data structure for arrays and dictionaries.</p>
<p><a name="array-literal-note" id="array-literal-note"></a></p>
<h2 id="toc112"><span><a href="more#array-literal">literal</a></span></h2>
<p>Array literal syntax.</p>
<p><strong>perl:</strong></p>
<p>Square brackets create an array and return a reference to it:</p>
<div class="code">
<pre>
<code>$a = [1,2,3]</code>
</pre></div>
<p><a name="quote-words-note" id="quote-words-note"></a></p>
<h2 id="toc113"><span><a href="more#quote-words">quote words</a></span></h2>
<p>The quote words operator, which is a literal for arrays of strings where each string contains a single word.</p>
<p><a name="array-size-note" id="array-size-note"></a></p>
<h2 id="toc114"><span><a href="more#array-size">size</a></span></h2>
<p>How to get the number of elements in an array.</p>
<p><strong>lua:</strong></p>
<p>The <tt>#</tt> operator returns the index of a non-nil value in the array that is followed by a nil value. Unfortunately different Lua implementations behave differently when there are multiple such indices. In particular there is no guarantee that the index will be the index of the last non-nil value in the array.</p>
<p><tt># a</tt> returns the number of times that a <tt>for</tt> loop used with <tt>ipairs</tt> will execute.</p>
<p><a name="array-lookup-note" id="array-lookup-note"></a></p>
<h2 id="toc115"><span><a href="more#array-lookup">lookup</a></span></h2>
<p>How to access a value in an array by index.</p>
<p><strong>perl:</strong></p>
<p>A negative index refers to the <em>length - index</em> element.</p>
<p><strong>lua:</strong></p>
<p>Lua arrays are indexed from one.</p>
<p><a name="array-update-note" id="array-update-note"></a></p>
<h2 id="toc116"><span><a href="more#array-update">update</a></span></h2>
<p>How to change the value stored in an array at given index.</p>
<p><a name="array-out-of-bounds-note" id="array-out-of-bounds-note"></a></p>
<h2 id="toc117"><span><a href="more#array-out-of-bounds">out-of-bounds behavior</a></span></h2>
<p>What happens when a lookup is performed on an out-of-bounds index.</p>
<p><a name="array-element-index-note" id="array-element-index-note"></a></p>
<h2 id="toc118"><span><a href="more#array-element-index">index of element</a></span></h2>
<p>How to get the first or last index containing a value.</p>
<p><strong>perl:</strong></p>
<p>Some <a href="http://www.perlmonks.org/?node_id=66003">techniques for getting the index of an array element</a>.</p>
<p><a name="array-slice-note" id="array-slice-note"></a></p>
<h2 id="toc119"><span><a href="more#array-slice">slice</a></span></h2>
<p>How to slice a subarray from an array.</p>
<p><strong>perl:</strong></p>
<p>Perl arrays can take an array of indices as the index value. The range of values selected can be discontinuous and the order of the values can be manipulated:</p>
<div class="code">
<pre>
<code>@nums = (1,2,3,4,5,6);                                                                                                                                                  
@nums[(1,3,2,4)];</code>
</pre></div>
<p><a name="array-slice-to-end-note" id="array-slice-to-end-note"></a></p>
<h2 id="toc120"><span><a href="more#array-slice-to-end">slice to end</a></span></h2>
<p>How to slice an array to the end</p>
<p><a name="array-back-note" id="array-back-note"></a></p>
<h2 id="toc121"><span><a href="more#array-back">manipulate back</a></span></h2>
<p>How to push or pop elements from the back an array. The return value of the pop command is the value of the item which is removed.</p>
<p>With these commands an array can be used as a stack.</p>
<p><a name="array-front-note" id="array-front-note"></a></p>
<h2 id="toc122"><span><a href="more#array-front">manipulate front</a></span></h2>
<p>How to shift or unshift elements to the front of an array. The return value of the shift command is the value of the item which is removed.</p>
<p>With these commands an array can be used as a stack. When combined with the commands from the previous section the array can be used as a queue.</p>
<p><a name="array-concat-note" id="array-concat-note"></a></p>
<h2 id="toc123"><span><a href="more#array-concat">concatenate</a></span></h2>
<p>How to concatenate two arrays.</p>
<p><a name="array-replicate-note" id="array-replicate-note"></a></p>
<h2 id="toc124"><span><a href="more#array-replicate">replicate</a></span></h2>
<p>How to create an array consisting of <em>n</em> copies of a value.</p>
<p><a name="array-copy-note" id="array-copy-note"></a></p>
<h2 id="toc125"><span><a href="more#array-copy">copy</a></span></h2>
<p>How to make an address copy, a shallow copy, and a deep copy of an array.</p>
<p>After an address copy is made, modifications to the copy also modify the original array.</p>
<p>After a shallow copy is made, the addition, removal, or replacement of elements in the copy does not modify of the original array. However, if elements in the copy are modified, those elements are also modified in the original array.</p>
<p>A deep copy is a recursive copy. The original array is copied and a deep copy is performed on all elements of the array. No change to the contents of the copy will modify the contents of the original array.</p>
<p><strong>perl:</strong></p>
<p>Taking a reference is customary way to make an address copy in Perl, but the Perl example is not equivalent to the other languages in that different syntax has to be used to access the original array and the address copy: <tt>@a</tt> and <tt>@$a1</tt>. To make <tt>@a1</tt> and <tt>@a</tt> refer to the same array, use typeglobs:</p>
<div class="code">
<pre>
<code>*a1 = *a;</code>
</pre></div>
<p><a name="array-arg-note" id="array-arg-note"></a></p>
<h2 id="toc126"><span><a href="more#array-arg">arrays as function arguments</a></span></h2>
<p>How arrays are passed as arguments.</p>
<p><a name="array-iter-note" id="array-iter-note"></a></p>
<h2 id="toc127"><span><a href="more#array-iter">iterate over elements</a></span></h2>
<p>How to iterate through the elements of an array.</p>
<p><strong>perl:</strong></p>
<p><tt>for</tt> and <tt>foreach</tt> are synonyms. Some use <tt>for</tt> exclusively for C-style for loops and <tt>foreach</tt> for array iteration.</p>
<p><a name="range-iteration-note" id="range-iteration-note"></a></p>
<h2 id="toc128"><span><a href="more#range-iteration">iterate over range</a></span></h2>
<p>Iterate over a range without instantiating it as a list.</p>
<p><strong>perl:</strong></p>
<p>With Perl 5.005 the <tt>for</tt> and <tt>foreach</tt> operators were optimized to not instantiate a range argument as a list.</p>
<p><a name="range-array-note" id="range-array-note"></a></p>
<h2 id="toc129"><span><a href="more#range-array">instantiate range as array</a></span></h2>
<p>How to convert a range to an array.</p>
<p><a name="array-reverse-note" id="array-reverse-note"></a></p>
<h2 id="toc130"><span><a href="more#array-reverse">reverse</a></span></h2>
<p>How to reverse the order of the elements in an array.</p>
<p><a name="array-sort-note" id="array-sort-note"></a></p>
<h2 id="toc131"><span><a href="more#array-sort">sort</a></span></h2>
<p>How to sort an array.</p>
<p><a name="array-dedupe-note" id="array-dedupe-note"></a></p>
<h2 id="toc132"><span><a href="more#array-dedupe">dedupe</a></span></h2>
<p>How to remove extra occurrences of elements from an array.</p>
<p><a name="membership-note" id="membership-note"></a></p>
<h2 id="toc133"><span><a href="more#membership">membership</a></span></h2>
<p>How to test whether a value is an element of an array; how to test whether a value is not an element of an array.</p>
<p><a name="intersection-note" id="intersection-note"></a></p>
<h2 id="toc134"><span><a href="more#intersection">intersection</a></span></h2>
<p>How to compute an intersection.</p>
<p><a name="union-note" id="union-note"></a></p>
<h2 id="toc135"><span><a href="more#union">union</a></span></h2>
<p>How to compute the union of two arrays.</p>
<p><a name="set-diff-note" id="set-diff-note"></a></p>
<h2 id="toc136"><span><a href="more#set-diff">relative complement</a></span></h2>
<p>How to find the elements of an array that are not in another array.</p>
<p><a name="map-note" id="map-note"></a></p>
<h2 id="toc137"><span><a href="more#map">map</a></span></h2>
<p>How to apply a function to the elements of an array.</p>
<p>None of the examples modify the source array.</p>
<p><strong>lua:</strong></p>
<p><a href="http://lua-users.org/wiki/FunctionalLibrary">map implementation</a></p>
<p><a name="filter-note" id="filter-note"></a></p>
<h2 id="toc138"><span><a href="more#filter">filter</a></span></h2>
<p>How to select the elements of an array for which a predicate is true.</p>
<p>None of the examples modify the source array.</p>
<p><strong>lua:</strong></p>
<p><a href="http://lua-users.org/wiki/FunctionalLibrary">filter implementation</a></p>
<p><a name="reduce-note" id="reduce-note"></a></p>
<h2 id="toc139"><span><a href="more#reduce">reduce</a></span></h2>
<p>How to reduce an array using a binary operation and an initial value.</p>
<p>None of the examples modify the source array.</p>
<p><strong>lua:</strong></p>
<p><a href="http://lua-users.org/wiki/FunctionalLibrary">reduce implementation</a></p>
<p><a name="universal-existential-test-note" id="universal-existential-test-note"></a></p>
<h2 id="toc140"><span><a href="more#universal-existential-test">universal and existential tests</a></span></h2>
<p>How to test whether all elements in an array satisfy a predicate; how to test whether at least one element in an array satisfies a predicate.</p>
<p><a name="shuffle-note" id="shuffle-note"></a></p>
<h2 id="toc141"><span><a href="more#shuffle">shuffle</a></span></h2>
<p>How to shuffle an array.</p>
<p><a name="zip-note" id="zip-note"></a></p>
<h2 id="toc142"><span><a href="more#zip">zip</a></span></h2>
<p>How to interleave arrays. In the case of two arrays the result is an array of pairs or an associative list.</p>
<p><strong>perl:</strong></p>
<p><tt>zip</tt> expects arrays as arguments, which makes it difficult to define the arrays to be zipped on the same line as the invocation. It can be done like this:</p>
<div class="code">
<pre>
<code>@a = zip @{[1,2,3]}, @{['a','b','c']};</code>
</pre></div>
<p><a name="dictionaries-note" id="dictionaries-note"></a></p>
<h1 id="toc143"><span><a href="more#dictionaries">Dictionaries</a></span></h1>
<p><a name="dict-literal-note" id="dict-literal-note"></a></p>
<h2 id="toc144"><span><a href="more#dict-literal">literal</a></span></h2>
<p>The syntax for a dictionary literal.</p>
<p><strong>perl:</strong></p>
<p>Curly brackets create a hash and return a reference to it:</p>
<div class="code">
<pre>
<code>$h = { 'hello' =&gt; 5, 'goodbye' =&gt; 7 }</code>
</pre></div>
<p><a name="dict-size-note" id="dict-size-note"></a></p>
<h2 id="toc145"><span><a href="more#dict-size">size</a></span></h2>
<p>How to get the number of entries in a dictionary.</p>
<p><a name="dict-lookup-note" id="dict-lookup-note"></a></p>
<h2 id="toc146"><span><a href="more#dict-lookup">lookup</a></span></h2>
<p>How to look up the value associated with a key.</p>
<p><strong>perl:</strong></p>
<p>Use the ampersand prefix <tt>@</tt> to slice a Perl hash. The index is a list of keys.</p>
<div class="code">
<pre>
<code>%nums = ('b'=&gt;1, 't'=&gt;2, 'a'=&gt;3);
@nums{('b','t')}</code>
</pre></div>
<p><a name="dict-update-note" id="dict-update-note"></a></p>
<h2 id="toc147"><span><a href="more#dict-update">update</a></span></h2>
<p>How to set or update the value associated with a key.</p>
<p><a name="dict-out-of-bounds-note" id="dict-out-of-bounds-note"></a></p>
<h2 id="toc148"><span><a href="more#dict-out-of-bounds">out of bounds behavior</a></span></h2>
<p>What happens when a lookup is performed for a key the dictionary does not have.</p>
<p><a name="dict-key-check-note" id="dict-key-check-note"></a></p>
<h2 id="toc149"><span><a href="more#dict-key-check">is key present</a></span></h2>
<p>How to find out whether a value is associated with a key.</p>
<p><a name="dict-delete-note" id="dict-delete-note"></a></p>
<h2 id="toc150"><span><a href="more#dict-delete">delete</a></span></h2>
<p>How to remove a key/value pair from a dictionary.</p>
<p><a name="dict-assoc-array-note" id="dict-assoc-array-note"></a></p>
<h2 id="toc151"><span><a href="more#dict-assoc-array">from array of pairs, from even length array</a></span></h2>
<p>How to create a dictionary from an array of pairs; how to create a dictionary from an even length array.</p>
<p><a name="dict-merge-note" id="dict-merge-note"></a></p>
<h2 id="toc152"><span><a href="more#dict-merge">merge</a></span></h2>
<p>How to merge the values of two dictionaries.</p>
<p>In the examples, if the dictionaries <tt>d1</tt> and {d2}} share keys then the values from <tt>d2</tt> will be used in the merged dictionary.</p>
<p><a name="dict-invert-note" id="dict-invert-note"></a></p>
<h2 id="toc153"><span><a href="more#dict-invert">invert</a></span></h2>
<p>How to turn a dictionary into its inverse. If a key 'foo' is mapped to value 'bar' by a dictionary, then its inverse will map the key 'bar' to the value 'foo'. However, if multiple keys are mapped to the same value in the original dictionary, then some of the keys will be discarded in the inverse.</p>
<p><a name="dict-iter-note" id="dict-iter-note"></a></p>
<h2 id="toc154"><span><a href="more#dict-iter">iteration</a></span></h2>
<p>How to iterate through all the key/value pairs of a dictionary.</p>
<p><a name="dict-key-val-array-note" id="dict-key-val-array-note"></a></p>
<h2 id="toc155"><span><a href="more#dict-key-val-array">keys and values as arrays</a></span></h2>
<p>How to convert the keys of a dictionary to an array; how to convert the values of a dictionary to an array.</p>
<p><a name="dict-sort-val-note" id="dict-sort-val-note"></a></p>
<h2 id="toc156"><span><a href="more#dict-sort-val">sort by values</a></span></h2>
<p>How to sort the data in a dictionary by its values.</p>
<p><a name="dict-default-val-note" id="dict-default-val-note"></a></p>
<h2 id="toc157"><span><a href="more#dict-default-val">default value, computed value</a></span></h2>
<p>How to create a dictionary with a default value for missing keys; how to compute and store the value on lookup.</p>
<p><strong>perl:</strong></p>
<p>How to use a <a href="http://www.perlmonks.org/?node_id=684059">tied hash</a>. If the CPAN module Tie::ExtraHash is installed there is <a href="http://www.perlmonks.org/?node_id=684069">a shorter way</a>.</p>
<p><a name="functions-note" id="functions-note"></a></p>
<h1 id="toc158"><span><a href="more#functions">Functions</a></span></h1>
<p>Python has both functions and methods. Ruby only has methods: functions defined at the top level are in fact methods on a special main object. Perl subroutines can be invoked with a function syntax or a method syntax.</p>
<p><a name="func-def-note" id="func-def-note"></a></p>
<h2 id="toc159"><span><a href="more#func-def">define function</a></span></h2>
<p>How to define a function.</p>
<p><strong>perl:</strong></p>
<p>One can also use <tt>shift</tt> to put the arguments into local variables:</p>
<div class="code">
<pre>
<code>sub add {
  my $a = shift;
  my $b = shift;

  $a + $b;
}</code>
</pre></div>
<p><a name="func-invocation-note" id="func-invocation-note"></a></p>
<h2 id="toc160"><span><a href="more#func-invocation">invoke function</a></span></h2>
<p>How to invoke a function.</p>
<p><a name="nested-func-note" id="nested-func-note"></a></p>
<h2 id="toc161"><span><a href="more#nested-func">nested function</a></span></h2>
<p>Can function definitions be nested; are nested functions visible outside of the function in which they are defined.</p>
<p><a name="missing-arg-note" id="missing-arg-note"></a></p>
<h2 id="toc162"><span><a href="more#missing-arg">missing argument behavior</a></span></h2>
<p>How incorrect number of arguments upon invocation are handled.</p>
<p><strong>perl:</strong></p>
<p>Perl collects all arguments into the @_ array, and subroutines normally don't declare the number of arguments they expect. However, this can be done with <a href="http://perldoc.perl.org/perlsub.html#Prototypes">prototypes</a>. Prototypes also provide a method for taking an array from the caller and giving a reference to the array to the callee.</p>
<p><a name="extra-arg-note" id="extra-arg-note"></a></p>
<h2 id="toc163"><span><a href="more#extra-arg">extra argument behavior</a></span></h2>
<p>If a function is invoked with more arguments than are declared, how the function can access them.</p>
<p><a name="default-arg-note" id="default-arg-note"></a></p>
<h2 id="toc164"><span><a href="more#default-arg">default argument</a></span></h2>
<p>How to declare a default value for an argument.</p>
<p><a name="var-arg-note" id="var-arg-note"></a></p>
<h2 id="toc165"><span><a href="more#var-arg">variable number of arguments</a></span></h2>
<p>How to write a function which accepts a variable number of argument.</p>
<p><strong>lua:</strong></p>
<p>In version 5.1 and earlier the global variable <tt>arg</tt> was set automatically. In version 5.2 one must explicitly assign to a local array.</p>
<p>It is possible to get the number of arguments that were provided without assigning to a local array:</p>
<div class="code">
<pre>
<code>function foo(...)
  print('passed ' .. select('#', ...) .. ' arguments')
end</code>
</pre></div>
<p><a name="retval-note" id="retval-note"></a></p>
<h2 id="toc166"><span><a href="more#retval">return value</a></span></h2>
<p>How the return value of a function is determined.</p>
<p><a name="multiple-retval-note" id="multiple-retval-note"></a></p>
<h2 id="toc167"><span><a href="more#multiple-retval">multiple return values</a></span></h2>
<p><strong>lua:</strong></p>
<p>If a function returns multiple values, the first value can be selected by placing the invocation inside parens:</p>
<div class="code">
<pre>
<code>function roots(x)
  return math.sqrt(x), -math.sqrt(x)
end
(roots(4))</code>
</pre></div>
<p><a name="lambda-decl-note" id="lambda-decl-note"></a></p>
<h2 id="toc168"><span><a href="more#lambda-decl">anonymous function literal</a></span></h2>
<p>How to define a lambda function.</p>
<p><a name="lambda-invocation-note" id="lambda-invocation-note"></a></p>
<h2 id="toc169"><span><a href="more#lambda-invocation">invoke anonymous function</a></span></h2>
<p>How to invoke a lambda function.</p>
<p><a name="func-as-val-note" id="func-as-val-note"></a></p>
<h2 id="toc170"><span><a href="more#func-as-val">function as value</a></span></h2>
<p>How to store a function in a variable and pass it as an argument.</p>
<p><a name="private-state-func-note" id="private-state-func-note"></a></p>
<h2 id="toc171"><span><a href="more#private-state-func">function with private state</a></span></h2>
<p>How to create a function with private state which persists between function invocations.</p>
<p><a name="default-scope-note" id="default-scope-note"></a></p>
<h2 id="toc172"><span><a href="more#default-scope">default scope</a></span></h2>
<p>What scope do variables declared inside a function have by default.</p>
<p><a name="execution-control-note" id="execution-control-note"></a></p>
<h1 id="toc173"><span><a href="more#execution-control">Execution Control</a></span></h1>
<p><a name="if-note" id="if-note"></a></p>
<h2 id="toc174"><span><a href="more#if">if</a></span></h2>
<p>The <tt>if</tt> statement.</p>
<p><strong>perl:</strong></p>
<p>When an <tt>if</tt> block is the last statement executed in a subroutine, the return value is the value of the branch that executed.</p>
<p><a name="while-note" id="while-note"></a></p>
<h2 id="toc175"><span><a href="more#while">while</a></span></h2>
<p>How to create a while loop.</p>
<p><strong>perl:</strong></p>
<p>Perl provides <tt>until</tt>, <tt>do-while</tt>, and <tt>do-until</tt> loops.</p>
<p>An <tt>until</tt> or a <tt>do-until</tt> loop can be replaced by a <tt>while</tt> or a <tt>do-while</tt> loop by negating the condition.</p>
<p><a name="break-continue-note" id="break-continue-note"></a></p>
<h2 id="toc176"><span><a href="more#break-continue">break and continue</a></span></h2>
<p><em>break</em> exits a <em>for</em> or <em>while</em> loop immediately. <em>continue</em> goes to the next iteration of the loop.</p>
<p><a name="for-note" id="for-note"></a></p>
<h2 id="toc177"><span><a href="more#for">for</a></span></h2>
<p>How to create a C-style for loop.</p>
<p><strong>lua:</strong></p>
<p>Provide a third argument to set the step size to something other than the default of one:</p>
<div class="code">
<pre>
<code>for i = 0, 90, 10 do
  print(i)
end</code>
</pre></div>
<p><a name="raise-exc-note" id="raise-exc-note"></a></p>
<h2 id="toc178"><span><a href="more#raise-exc">raise exception</a></span></h2>
<p>How to raise an exception.</p>
<p><a name="catch-exc-note" id="catch-exc-note"></a></p>
<h2 id="toc179"><span><a href="more#catch-exc">catch exception</a></span></h2>
<p>How to handle an exception.</p>
<p><a name="finally-ensure-note" id="finally-ensure-note"></a></p>
<h2 id="toc180"><span><a href="more#finally-ensure">finally/ensure</a></span></h2>
<p>Clauses that are guaranteed to be executed even if an exception is thrown or caught.</p>
<p><a name="uncaught-exc-note" id="uncaught-exc-note"></a></p>
<h2 id="toc181"><span><a href="more#uncaught-exc">uncaught exception behavior</a></span></h2>
<p>System behavior if an exception goes uncaught. Most interpreters print the exception message to stderr and exit with a nonzero status.</p>
<p><a name="closure-note" id="closure-note"></a></p>
<h2 id="toc182"><span><a href="more#closure">closure</a></span></h2>
<p>How to create a first class function with access to the local variables of the local scope in which it was created.</p>
<p><a name="generator-note" id="generator-note"></a></p>
<h2 id="toc183"><span><a href="more#generator">generator</a></span></h2>
<p>How to create and use a generator.</p>
<p><a name="streams-note" id="streams-note"></a></p>
<h1 id="toc184"><span><a href="more#streams">Streams</a></span></h1>
<p><a name="print-to-stdout-note" id="print-to-stdout-note"></a></p>
<h2 id="toc185"><span><a href="more#print-to-stdout">print to standard output</a></span></h2>
<p><a name="read-stdin-note" id="read-stdin-note"></a></p>
<h2 id="toc186"><span><a href="more#read-stdin">read from standard input</a></span></h2>
<p>How to read a line from standard input.</p>
<p><a name="standard-file-handles-note" id="standard-file-handles-note"></a></p>
<h2 id="toc187"><span><a href="more#standard-file-handles">standard file handles</a></span></h2>
<p>Constands for the standard file handles.</p>
<p><a name="open-file-note" id="open-file-note"></a></p>
<h2 id="toc188"><span><a href="more#open-file">open file</a></span></h2>
<p>How to create a file handle for reading.</p>
<p><a name="open-file-write-note" id="open-file-write-note"></a></p>
<h2 id="toc189"><span><a href="more#open-file-write">open file for writing</a></span></h2>
<p>How to create a file handle for writing.</p>
<p><a name="close-file-note" id="close-file-note"></a></p>
<h2 id="toc190"><span><a href="more#close-file">close file</a></span></h2>
<p>How to close a file handle.</p>
<p><a name="read-line-note" id="read-line-note"></a></p>
<h2 id="toc191"><span><a href="more#read-line">read line</a></span></h2>
<p><a name="file-iter-note" id="file-iter-note"></a></p>
<h2 id="toc192"><span><a href="more#file-iter">iterate over a file by line</a></span></h2>
<p><a name="chomp-note" id="chomp-note"></a></p>
<h2 id="toc193"><span><a href="more#chomp">chomp</a></span></h2>
<p>Remove a newline, carriage return, or carriage return newline pair from the end of a line if there is one.</p>
<p><a name="read-file-note" id="read-file-note"></a></p>
<h2 id="toc194"><span><a href="more#read-file">read file</a></span></h2>
<p><a name="write-file-note" id="write-file-note"></a></p>
<h2 id="toc195"><span><a href="more#write-file">write to file</a></span></h2>
<p><a name="flush-file-note" id="flush-file-note"></a></p>
<h2 id="toc196"><span><a href="more#flush-file">flush file handle</a></span></h2>
<p><a name="files-note" id="files-note"></a></p>
<h1 id="toc197"><span><a href="more#files">Files</a></span></h1>
<p><a name="file-test-note" id="file-test-note"></a></p>
<h2 id="toc198"><span><a href="more#file-test">file exists test, file regular test</a></span></h2>
<p><a name="file-cp-rm-mv-note" id="file-cp-rm-mv-note"></a></p>
<h2 id="toc199"><span><a href="more#file-cp-rm-mv">copy file, remove file, rename file</a></span></h2>
<p><a name="chmod-note" id="chmod-note"></a></p>
<h2 id="toc200"><span><a href="more#chmod">set file permissions</a></span></h2>
<p><a name="tmpfile-note" id="tmpfile-note"></a></p>
<h2 id="toc201"><span><a href="more#tmpfile">temporary file</a></span></h2>
<p><a name="directories-note" id="directories-note"></a></p>
<h1 id="toc202"><span><a href="more#directories">Directories</a></span></h1>
<p><a name="processes-environment-note" id="processes-environment-note"></a></p>
<h1 id="toc203"><span><a href="more#processes-environment">Processes and Environment</a></span></h1>
<p><a name="cmd-line-arg-note" id="cmd-line-arg-note"></a></p>
<h2 id="toc204"><span><a href="more#cmd-line-arg">command line arguments</a></span></h2>
<p>How to access the command line arguments.</p>
<p><a name="env-var-note" id="env-var-note"></a></p>
<h2 id="toc205"><span><a href="more#env-var">environment variable</a></span></h2>
<p>How to access an environment variable.</p>
<p><a name="exit-note" id="exit-note"></a></p>
<h2 id="toc206"><span><a href="more#exit">exit</a></span></h2>
<p>How to terminate the process and set the status code.</p>
<p><a name="set-signal-handler-note" id="set-signal-handler-note"></a></p>
<h2 id="toc207"><span><a href="more#set-signal-handler">set signal handler</a></span></h2>
<p>How to register a signal handler.</p>
<p><a name="external-cmd-note" id="external-cmd-note"></a></p>
<h2 id="toc208"><span><a href="more#external-cmd">external command</a></span></h2>
<p>How to execute an external command.</p>
<p><a name="backticks-note" id="backticks-note"></a></p>
<h2 id="toc209"><span><a href="more#backticks">backticks</a></span></h2>
<p>How to execute an external command and read the standard output into a variable.</p>
<p><a name="libraries-namespaces-note" id="libraries-namespaces-note"></a></p>
<h1 id="toc210"><span><a href="more#libraries-namespaces">Libraries and Namespaces</a></span></h1>
<p><a name="lib-note" id="lib-note"></a></p>
<h2 id="toc211"><span><a href="more#lib">library</a></span></h2>
<p>What a library looks like.</p>
<p><a name="import-lib-note" id="import-lib-note"></a></p>
<h2 id="toc212"><span><a href="more#import-lib">import library</a></span></h2>
<p>How to import a library.</p>
<p><a name="lib-path-note" id="lib-path-note"></a></p>
<h2 id="toc213"><span><a href="more#lib-path">library path</a></span></h2>
<p>How to access the library path.</p>
<p><a name="lib-path-env-note" id="lib-path-env-note"></a></p>
<h2 id="toc214"><span><a href="more#lib-path-env">library path environment variable</a></span></h2>
<p>The environment variable which governs the library path.</p>
<p><a name="namespace-decl-note" id="namespace-decl-note"></a></p>
<h2 id="toc215"><span><a href="more#namespace-decl">namespace declaration</a></span></h2>
<p>How to declare a namespace.</p>
<p><a name="namespace-separator-note" id="namespace-separator-note"></a></p>
<h2 id="toc216"><span><a href="more#namespace-separator">namespace separator</a></span></h2>
<p>The separator used in namespace names.</p>
<p><a name="pkg-management-note" id="pkg-management-note"></a></p>
<h2 id="toc217"><span><a href="more#pkg-management">list installed packages, install a package</a></span></h2>
<p>How to list the installed 3rd party packages; how to install a 3rd party package.</p>
<p><a name="objects-note" id="objects-note"></a></p>
<h1 id="toc218"><span><a href="more#objects">Objects</a></span></h1>
<p><a name="def-class-note" id="def-class-note"></a></p>
<h2 id="toc219"><span><a href="more#def-class">define class</a></span></h2>
<p>How to define a class.</p>
<p><a name="create-obj-note" id="create-obj-note"></a></p>
<h2 id="toc220"><span><a href="more#create-obj">create object</a></span></h2>
<p>How to instantiate a class.</p>
<p><a name="blank-obj-note" id="blank-obj-note"></a></p>
<h2 id="toc221"><span><a href="more#blank-obj">create blank object</a></span></h2>
<p>How to create a blank object without any attributes or methods, or at least without any but the default attributes and methods.</p>
<p><a name="instance-var-visibility-note" id="instance-var-visibility-note"></a></p>
<h2 id="toc222"><span><a href="more#instance-var-visibility">instance variable visibility</a></span></h2>
<p><a name="obj-literal-note" id="obj-literal-note"></a></p>
<h2 id="toc223"><span><a href="more#obj-literal">object literal</a></span></h2>
<p>The syntax for an object literal.</p>
<p><a name="set-attr-note" id="set-attr-note"></a></p>
<h2 id="toc224"><span><a href="more#set-attr">set attribute</a></span></h2>
<p>How to set an object attribute.</p>
<p><a name="get-attr-note" id="get-attr-note"></a></p>
<h2 id="toc225"><span><a href="more#get-attr">get attribute</a></span></h2>
<p>How to get an object attribute.</p>
<p><a name="def-method-note" id="def-method-note"></a></p>
<h2 id="toc226"><span><a href="more#def-method">define method</a></span></h2>
<p>How to define a method for an object.</p>
<p><a name="invoke-method-note" id="invoke-method-note"></a></p>
<h2 id="toc227"><span><a href="more#invoke-method">invoke method</a></span></h2>
<p>How to invoke an object method.</p>
<p><a name="method-missing-note" id="method-missing-note"></a></p>
<h2 id="toc228"><span><a href="more#method-missing">handle undefined method invocation</a></span></h2>
<p><a name="def-class-method-note" id="def-class-method-note"></a></p>
<h2 id="toc229"><span>define class method</span></h2>
<p><a name="invoke-class-method-note" id="invoke-class-method-note"></a></p>
<h2 id="toc230"><span>invoke class method</span></h2>
<p><a name="def-class-var-note" id="def-class-var-note"></a></p>
<h2 id="toc231"><span>define class variable</span></h2>
<p><a name="get-set-class-var-note" id="get-set-class-var-note"></a></p>
<h2 id="toc232"><span><a href="more#get-set-class-var">get and set class variable</a></span></h2>
<p><a name="inheritance-polymorphism-note" id="inheritance-polymorphism-note"></a></p>
<h1 id="toc233"><span><a href="more#inheritance-polymorphism">Inheritance and Polymorphism</a></span></h1>
<p><a name="subclass-note" id="subclass-note"></a></p>
<h2 id="toc234"><span><a href="more#subclass">subclass</a></span></h2>
<p><a name="reflection-note" id="reflection-note"></a></p>
<h1 id="toc235"><span><a href="more#reflection">Reflection</a></span></h1>
<p><a name="inspect-type-note" id="inspect-type-note"></a></p>
<h2 id="toc236"><span><a href="more#inspect-type">inspect type</a></span></h2>
<p><a name="basic-types-note" id="basic-types-note"></a></p>
<h2 id="toc237"><span><a href="more#basic-types">basic types</a></span></h2>
<p><a name="inspect-class-note" id="inspect-class-note"></a></p>
<h2 id="toc238"><span><a href="more#inspect-class">inspect class</a></span></h2>
<p><a name="has-method-note" id="has-method-note"></a></p>
<h2 id="toc239"><span><a href="more#has-method">has method?</a></span></h2>
<p><a name="msg-passing-note" id="msg-passing-note"></a></p>
<h2 id="toc240"><span><a href="more#msg-passing">message passing</a></span></h2>
<p><a name="eval-note" id="eval-note"></a></p>
<h2 id="toc241"><span><a href="more#eval">eval</a></span></h2>
<p><a name="methods-note" id="methods-note"></a></p>
<h2 id="toc242"><span><a href="more#methods">list object methods</a></span></h2>
<p><a name="attributes-note" id="attributes-note"></a></p>
<h2 id="toc243"><span><a href="more#attributes">list object attributes</a></span></h2>
<p><a name="loaded-lib-note" id="loaded-lib-note"></a></p>
<h2 id="toc244"><span><a href="more#loaded-lib">list loaded libraries</a></span></h2>
<p><a name="loaded-namespaces-note" id="loaded-namespaces-note"></a></p>
<h2 id="toc245"><span><a href="more#loaded-namespaces">list loaded namespaces</a></span></h2>
<p><a name="inspect-namespace-note" id="inspect-namespace-note"></a></p>
<h2 id="toc246"><span><a href="more#inspect-namespace">inspect namespace</a></span></h2>
<p><a name="pretty-print-note" id="pretty-print-note"></a></p>
<h2 id="toc247"><span><a href="more#pretty-print">pretty print</a></span></h2>
<p><a name="src-line-file-note" id="src-line-file-note"></a></p>
<h2 id="toc248"><span><a href="more#src-line-file">source line number and file name</a></span></h2>
<p><a name="cmd-line-doc-note" id="cmd-line-doc-note"></a></p>
<h2 id="toc249"><span><a href="more#cmd-line-doc">command line documentation</a></span></h2>
<p><a name="net-web-note" id="net-web-note"></a></p>
<h1 id="toc250"><span><a href="more#net-web">Net and Web</a></span></h1>
<p><a name="hostname-ip-note" id="hostname-ip-note"></a></p>
<h2 id="toc251"><span><a href="more#hostname-ip">get local hostname, dns lookup, reverse dns lookup</a></span></h2>
<p>How to get the hostname and the ip address of the local machine without connecting to a socket.</p>
<p>The operating system should provide a method for determining the hostname. Linux provides the <tt>uname</tt> system call.</p>
<p>A DNS lookup can be performed to determine the IP address for the local machine. This may fail if the DNS server is unaware of the local machine or if the DNS server has incorrect information about the local host.</p>
<p>A reverse DNS lookup can be performed to find the hostname associated with an IP address. This may fail for the same reasons a forward DNS lookup might fail.</p>
<p><a name="http-get-note" id="http-get-note"></a></p>
<h2 id="toc252"><span><a href="more#http-get">http get</a></span></h2>
<p>How to make an HTTP GET request and read the response into a string.</p>
<p><a name="http-post-note" id="http-post-note"></a></p>
<h2 id="toc253"><span><a href="more#http-post">http post</a></span></h2>
<p><a name="absolute-url-note" id="absolute-url-note"></a></p>
<h2 id="toc254"><span><a href="more#absolute-url">absolute url</a></span></h2>
<p>How to construct an absolute URL from a base URL and a relative URL as documented in <a href="http://www.ietf.org/rfc/rfc1808.txt">RFC 1808</a>.</p>
<p>When constructing the absolute URL, the rightmost path component of the base URL is removed unless it ends with a slash /. The query string and fragment of the base URL are always removed.</p>
<p>If the relative URL starts with a slash / then the entire path of the base URL is removed.</p>
<p>If the relative URL starts with one or more occurrences of ../ then one or more path components are removed from the base URL.</p>
<p>The base URL and the relative URL will be joined by a single slash / in the absolute URL.</p>
<p><a name="parse-url-note" id="parse-url-note"></a></p>
<h2 id="toc255"><span><a href="more#parse-url">parse url</a></span></h2>
<p>How to extract the protocol, host, port, path, query string, and fragment from a URL. How to extract the parameters from the query string.</p>
<p><a name="url-encode-note" id="url-encode-note"></a></p>
<h2 id="toc256"><span><a href="more#url-encode">url encode/decode</a></span></h2>
<p>How to URL encode and URL unencode a string.</p>
<p>URL encoding, also called percent encoding, is described in <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>. It replaces all characters except for the letters, digits, and a few punctuation marks with a percent sign followed by their two digit hex encoding. The characters which are not escaped are:</p>
<div class="code">
<pre>
<code>A-Z a-z 0-9 - _ . ~</code>
</pre></div>
<p>URL encoding can be used to encode UTF-8, in which case each byte of a UTF-8 character is encoded separately.</p>
<p>When form data is sent from a browser to a server via an HTTP GET or an HTTP POST, the data is percent encoded but spaces are replaced by plus signs <tt>+</tt> instead of <tt>%20</tt>. The MIME type for form data is <tt>application/x-www-form-urlencoded</tt>.</p>
<p><a name="base64-note" id="base64-note"></a></p>
<h2 id="toc257"><span><a href="more#base64">base64 encode/decode</a></span></h2>
<p>How to encode binary data in ASCII using the Base64 encoding scheme.</p>
<p>A popular Base64 encoding is the one defined by <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> for MIME. Every 3 bytes of input is mapped to 4 of these characters: <tt>[A-Za-z0-9/+]</tt>.<br />
If the input does not consist of a multiple of three characters, then the output is padded with one or two hyphens: =.</p>
<p>Whitespace can inserted freely into Base64 output; this is necessary to support transmission by email. When converting Base64 back to binary whitespace is ignored.</p>
<p><a name="unit-tests-note" id="unit-tests-note"></a></p>
<h1 id="toc258"><span><a href="more#unit-tests">Unit Tests</a></span></h1>
<p><a name="test-class-note" id="test-class-note"></a></p>
<h2 id="toc259"><span><a href="more#test-class">test class</a></span></h2>
<p><a name="run-test-note" id="run-test-note"></a></p>
<h2 id="toc260"><span><a href="more#run-test">run tests, run test method</a></span></h2>
<p><a name="assert-equal-note" id="assert-equal-note"></a></p>
<h2 id="toc261"><span><a href="more#assert-equal">equality assertion</a></span></h2>
<p><a name="assert-approx-note" id="assert-approx-note"></a></p>
<h2 id="toc262"><span><a href="more#assert-approx">approximate assertion</a></span></h2>
<p><a name="assert-regex-note" id="assert-regex-note"></a></p>
<h2 id="toc263"><span><a href="more#assert-regex">regex assertion</a></span></h2>
<p><a name="assert-exc-note" id="assert-exc-note"></a></p>
<h2 id="toc264"><span><a href="more#assert-exc">exception assertion</a></span></h2>
<p><a name="test-setup-note" id="test-setup-note"></a></p>
<h2 id="toc265"><span><a href="more#test-setup">setup</a></span></h2>
<p><a name="test-teardown-note" id="test-teardown-note"></a></p>
<h2 id="toc266"><span><a href="more#test-teardown">teardown</a></span></h2>
<p><a name="debugging-profiling-note" id="debugging-profiling-note"></a></p>
<h1 id="toc267"><span><a href="more#debugging-profiling">Debugging and Profiling</a></span></h1>
<p><a name="check-syntax-note" id="check-syntax-note"></a></p>
<h2 id="toc268"><span><a href="more#check-syntax">check syntax</a></span></h2>
<p><a name="warning-flag-note" id="warning-flag-note"></a></p>
<h2 id="toc269"><span><a href="more#warning-flag">flags for stronger and strongest warnings</a></span></h2>
<p><a name="lint-note" id="lint-note"></a></p>
<h2 id="toc270"><span><a href="more#lint">lint</a></span></h2>
<p><a name="debugger-note" id="debugger-note"></a></p>
<h2 id="toc271"><span><a href="more#debugger">debugger</a></span></h2>
<p><a name="debugger-cmd-note" id="debugger-cmd-note"></a></p>
<h2 id="toc272"><span><a href="more#debugger-cmd">debugger commands</a></span></h2>
<p><a name="benchmark-code-note" id="benchmark-code-note"></a></p>
<h2 id="toc273"><span><a href="more#benchmark-code">benchmark code</a></span></h2>
<p><a name="profile-code-note" id="profile-code-note"></a></p>
<h2 id="toc274"><span><a href="more#profile-code">profile code</a></span></h2>
<p><a name="perl" id="perl"></a></p>
<h1 id="toc275"><span><a href="more#top">Perl</a></span></h1>
<p><a href="http://perldoc.perl.org/index-language.html">perldoc</a><br />
<a href="http://perldoc.perl.org/index-modules-A.html">core modules</a></p>
<p>The first character of a Perl variable <tt>$ @ %</tt> determines the type of value that can be stored in the variable: scalar, array, hash. Using an array variable <tt>@foo</tt> in a scalar context yields the size of the array, and assigning a scalar to an array will modify the array to contain a single element. <tt>$foo[0]</tt> accesses the first element of the array <tt>@foo</tt>, and <tt>$bar{'hello'}</tt> accesses the value stored under <tt>'hello'</tt> in the hash <tt>%bar</tt>. <tt>$#foo</tt> is the index of the last element in the array <tt>@foo</tt>.</p>
<p>Scalars can store a string, integer, or float. If an operator is invoked on a scalar which contains an incorrect data type, perl will perform an implicit conversion to the correct data type: non-numeric strings evaluate to zero.</p>
<p>Scalars can also contain a reference to a variable, which can be created with a backslash: <tt>$baz = \@foo;</tt> The original value can be dereferenced with the correct prefix: <tt>@$baz</tt>. References are how perl creates complex data structures, such as arrays of hashes and arrays of arrays. If <tt>$baz</tt> contains a reference to an array, then <tt>$baz-&gt;[0]</tt> is the first element of the array. if <tt>$baz</tt> contains a reference to a hash, <tt>$baz-&gt;{'hello'}</tt> is the value indexed by <tt>'hello'</tt>.</p>
<p>The literals for arrays and hashes are parens with comma separated elements. Hash literals must contain an even number of elements, and the <tt>=&gt;</tt> operator can be used in placed of a comma between a key and its value. Square brackets, e.g. <tt>[1, 2, 3]</tt>, create an array and return a reference to it, and curly brackets, e.g. <tt>{'hello' =&gt; 5, 'bye' =&gt; 3}</tt> , create a hash and return a reference to it.</p>
<p>By default Perl variables are global. They can be made local to the containing block with the <tt>my</tt> keyword or the <tt>local</tt> keyword. <tt>my</tt> gives lexical scope, and <tt>local</tt> gives dynamic scope. Also by default, the perl interpreter creates a variable whenever it encounters a new variable name in the code. The <tt>use strict;</tt> pragma requires that all variables be declared with <tt>my</tt>, <tt>local</tt>, or <tt>our</tt>. The last is used to declare global variables.</p>
<p>Perl functions do not declare their arguments. Any arguments passed to the function are available in the <tt>@_</tt> array, and the shift command will operate on this array if no argument is specified. An array passed as an argument is expanded: if the array contains 10 elements, the callee will have 10 arguments in its <tt>@_</tt> array. A reference (passing <tt>\@foo</tt> instead of <tt>@foo</tt>) can be used to prevent this.</p>
<p>Some of Perl’s special variables:</p>
<ul>
<li><tt>$$</tt>: pid of the perl process</li>
<li><tt>$0</tt>: name of the file containing the perl script (may be a full pathname)</li>
<li><tt>$@</tt>: error message from last eval or require command</li>
<li><tt>$&amp; $` $’</tt>: what last regex matched, part of the string before and after the match</li>
<li><tt>$1</tt> … <tt>$9</tt>: what subpatterns in last regex matched</li>
</ul>
<p><a name="lua" id="lua"></a></p>
<h1 id="toc276"><span><a href="more#top">Lua</a></span></h1>
<p><a href="http://www.lua.org/manual/5.1/manual.html">Lua 5.1 Reference Manual</a><br />
<a href="http://lua-users.org/wiki/TutorialDirectory">Lua Tutorial Directory</a></p>
<p>The Lua REPL is actually a REL; that is, it doesn't print the value of statement. Furthermore expressions cannot in general be used in the position of a statement. An expression can be converted to a statement and printed by preceding it with an equals sign:</p>
<div class="code">
<pre>
<code>&gt; =1 + 1
2
&gt; ="lorem ipsum"
lorem ipsum</code>
</pre></div>
<p>There is no built-in pretty printer for tables. All numbers are stored as double precision floats. The table type can be used as both an array and a dictionary.</p>
<p><a name="groovy" id="groovy"></a></p>
<h1 id="toc277"><span><a href="more#top">Groovy</a></span></h1>
<p><a href="http://groovy.codehaus.org/User+Guide">User Guide</a></p>
<p>An interpreted Groovy script can be nothing more than a few top level statements which are executed in order. The Groovy interpreter handles providing an entry point class and main method, compiling the source to Java byte code, and launching the JVM.</p>
<div class="code">
<pre>
<code>$ cat &gt; hello.groovy
s = "Hello, World!"
println(s)

$ groovy hello.groovy
Hello, World!</code>
</pre></div>
<p>Groovy classes can be placed in their own files and compiled to Java byte code explicitly. The resulting <tt>.class</tt> files depend on the groovy.jar and the asm.jar but otherwise can be used like <tt>.class</tt> files compiled from Java source files.</p>
<div class="code">
<pre>
<code>$ cat &gt; Greeting.groovy
class Greeting {
  void say(name) {
    println("Hello, ${name}!")
  }
}

$ cat &gt; UseGreeting.java
public class UseGreeting {
  public static void main(String[] args) {
    Greeting g = new Greeting();
    g.say(args[0]);
  }
}

$ groovyc Greeting.groovy

$ javac UseGreeting.java

$ java -cp.:/PATH/TO/groovy-2.2.1.jar:/PATH/TO/asm-4.1.jar UseGreeting Fred
Hello, Fred!</code>
</pre></div>
<p>All Groovy values have a Java type which can be inspected at runtime with the <tt>getClass()</tt> method.</p>
<p>A Groovy variable can optionally be declared to have a type. This places a constraint on the values which can be stored in the variable which is enforced at run time. The following code generates a <tt>org.codehaus.groovy.runtime.typehandling.GroovyCastException</tt>:</p>
<div class="code">
<pre>
<code>Integer i = 'foo'</code>
</pre></div>
<p>Groovy does not use any of the Java primitive types directly: <tt>byte</tt>, <tt>short</tt>, <tt>int</tt>, <tt>long</tt>, <tt>float</tt>, <tt>double</tt>, <tt>boolean</tt>, <tt>char</tt>. Instead it used it uses the wrapper classes: <tt>Byte</tt>, <tt>Short</tt>, <tt>Integer</tt>, <tt>Long</tt>, <tt>Float</tt>, <tt>Double</tt>, <tt>Boolean</tt>, <tt>Char</tt>. Nevertheless it is still possible to use the primitive type in a variable declaration.</p>
<p>Groovy performs the following imports:</p>
<div class="code">
<pre>
<code>import java.lang.*
import java.util.*
import java.io.*
import java.net.*
import groovy.lang.*
import groovy.util.*
import java.math.BigInteger
import java.math.BigDecimal</code>
</pre></div>

                    </div>
        </div>
      </div>
      <div id="license-area" class="license-area">
        <a href="https://github.com/clarkgrubb/hyperpolyglot/issues">issue tracker</a> |
        content of this page licensed under
        <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">
        creative commons attribution-sharealike 3.0</a>
        <br>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-17129977-2']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

</body>
</html>