a side-by-side reference sheet sheet one:arithmetic and logic|strings|regexes|dates and time|arrays|dictionaries|functions|execution control files|directories|processes and environment sheet two:libraries and modules|objects|reflection|web a side-by-side reference sheetsheet one: arithmetic and logic | strings | regexes | dates and time | arrays | dictionaries | functions | execution control files | directories | processes and environmentsheet two: libraries and modules | objects | reflection | web | tests | debugging and profiling | java interop | contactphp (1995)perl (1987)python (1991)ruby (1995)versions used 5.35.12; 5.142.7; 3.21.8; 1.9implicit prologuenoneuse strict;import os, re, sysnoneshow version $ php --version$ perl --version$ python -V$ ruby --versioninterpreter $ php -f foo.php$ perl foo.pl$ python foo.py$ ruby foo.rbrepl $ php$ perl -de 0$ python$ irbcommand line script$ php -r 'echo "hi\n";'$ perl -e 'print("hi\n")'$ python -c "print('hi')"$ ruby -e 'puts "hi"'statement separator ;statements must be semicolon terminated inside {};newline or ;newlines not separators inside (), [], {}, triple quote literals, or after backslash: \newline or ;newlines not separators inside (), [], {}, ``, '', "", or after binary operator or backslash: \block delimiters {}{}offside rule{}do endassignment $v = 1;$v = 1;assignments can be chained but otherwise don't return values:v = 1v = 1parallel assignment list($x, $y, $z) = array(1 ,2, 3);# 3 is discarded:list($x, $y) = array(1, 2, 3);# $z set to NULL:list($x, $y, $z) = array(1, 2);($x, $y, $z) = (1, 2, 3);# 3 is discarded:($x, $y) = (1, 2, 3);# $z set to undef:($x, $y, $z) = (1, 2);x, y, z = 1, 2, 3# raises ValueError:x, y = 1, 2, 3# raises ValueError:x, y, z = 1, 2x, y, z = 1, 2, 3# 3 is discarded:x, y = 1, 2, 3# z set to nil:x, y, z = 1, 2swap list($x, $y) = array($y, $x);($x, $y) = ($y, $x);x, y = y, xx, y = y, xcompound assignment operators: arithmetic, string, logical, bit+= -= *= none /= %= **=.= none&= |= none= &= |= ^=+= -= *= none /= %= **=.= x=&&= ||= ^== &= |= ^=# do not return values:+= -= *= /= //= %= **=+= *=&= |= ^== &= |= ^=+= -= *= /= none %= **=+= *=&&= ||= ^== &= |= ^=increment and decrement $x = 1;$y = ++$x;$z = --$y;my $x = 1;my $y = ++$x;my $z = --$y;nonex = 1# x and y not mutated:y = x.succz = y.predlocal variable declarations # in function body:$v = NULL;$a = array();$d = array();$x = 1;list($y, $z) = array(2, 3);my $v;my (@a, %d);my $x = 1;my ($y, $z) = (2, 3);# in function body:v = Nonea, d = [], {}x = 1y, z = 2, 3v = nila, d = [], {}x = 1y, z = 2, 3regions which define local scopetop level: function or method bodynestable (with use clause): anonymous function bodytop level: filenestable: function body anonymous function body anonymous blocknestable (read only): function or method bodytop level: file class block module block method bodynestable: anonymous function block anonymous blockglobal variablelist($g1, $g2) = array(7, 8);function swap_globals() { global $g1, $g2; list($g1, $g2) = array($g2, $g1);}our ($g1, $g2) = (7, 8);sub swap_globals { ($g1, $g2) = ($g2, $g1);}g1, g2 = 7, 8def swap_globals(): global g1, g2 g1, g2 = g2, g1$g1, $g2 = 7, 8def swap_globals $g1, $g2 = $g2, $g1endconstant declaration define("PI", 3.14);use constant PI => 3.14;# uppercase identifiers# constant by conventionPI = 3.14# warning if capitalized# identifier is reassignedPI = 3.14to-end-of-line comment // comment# comment# comment# comment# commentcomment out multiple lines /* comment lineanother line */=forcomment lineanother line=cutuse triple quote string literal:'''comment lineanother line'''=begincomment lineanother line=endnull NULL # case insensitiveundefNonenilnull test is_null($v)! isset($v)! defined $vv == Nonev is Nonev == nilv.nil?undefined variable access NULLerror under use strict; otherwise undefraises NameErrorraises NameErrorundefined test same as null test; no distinction between undefined variables and variables set to NULLsame as null test; no distinction between undefined variables and variables set to undefnot_defined = Falsetry: vexcept NameError: not_defined = True! defined?(v)arithmetic and logic phpperlpythonrubytrue and false TRUE FALSE # case insensitve1 ""True Falsetrue falsefalsehoods FALSE NULL 0 0.0 "" "0" array()undef 0 0.0 "" "0" ()False None 0 0.0 '' [] {}false nillogical operators && || !lower precedence:and or xor&& || !lower precedence:and or xor notand or not&& || !lower precedence:and or notconditional expression $x > 0 ? $x : -$x$x > 0 ? $x : -$xx if x > 0 else -xx > 0 ? x : -xcomparison operators == != or > = no conversion: === !==numbers only: == != > = strings: eq ne gt lt ge lecomparison operators are chainable:== != > = == != > = three value comparisonnone0 1"do" cmp "re"removed from Python 3:cmp(0, 1)cmp('do', 're')0 1"do" "re"convert from string, to string 7 + "12"73.9 + ".037""value: " . 87 + "12"73.9 + ".037""value: " . 87 + int('12')73.9 + float('.037')'value: ' + str(8)7 + "12".to_i73.9 + ".037".to_f"value: " + "8".to_sarithmetic operators + - * / none % pow(b,e)+ - * / none % **+ - * / // % **+ - * x.fdiv(y) / % **integer division and divmod (int) (13 / 5)noneint ( 13 / 5 )none13 // 5q, r = divmod(13, 5)13 / 5q, r = 13.divmod(5)float division 13 / 513 / 5float(13) / 5# Python 3:13 / 513.to_f / 5 or13.fdiv(5)arithmetic functions sqrt exp log sin cos tan asin acos atan atan2use Math::Trig qw( tan asin acos atan);sqrt exp log sin cos tan asin acos atan atan2from math import sqrt, exp, log, \sin, cos, tan, asin, acos, atan, atan2include Mathsqrt exp log sin cos tan asin acos atan atan2arithmetic truncation (int)$xround($x)ceil($x)floor($x)abs($x)# cpan -i Number::Formatuse Number::Format 'round';use POSIX qw(ceil floor);int($x)round($x, 0)ceil($x)floor($x)abs($x)import mathint(x)int(round(x))math.ceil(x)math.floor(x)abs(x)x.to_ix.roundx.ceilx.floorx.absmin and max min(1,2,3)max(1,2,3)$a = array(1,2,3)min($a)max($a)use List::Util qw(min max);min(1,2,3);max(1,2,3);@a = (1,2,3);min(@a);max(@a);min(1,2,3)max(1,2,3)min([1,2,3])max([1,2,3])[1,2,3].min[1,2,3].maxdivision by zero returns FALSE with warningerrorraises ZeroDivisionErrorinteger division raises ZeroDivisionErrorfloat division returns Infinityinteger overflow converted to floatconverted to float; use Math::BigInt to create arbitrary length integersbecomes arbitrary length integer of type longbecomes arbitrary length integer of type Bignumfloat overflow INFinfraises OverflowErrorInfinitysqrt -2 NaNerror unless use Math::Complex in effect# raises ValueError:import mathmath.sqrt(-2)# returns complex float:import cmathcmath.sqrt(-2)raises Errno::EDOMrational numbers noneuse Math::BigRat;my $x = Math::BigRat->new("22/7");$x->numerator();$x->denominator();from fractions import Fractionx = Fraction(22,7)x.numeratorx.denominatorrequire 'rational'x = Rational(22,7)x.numeratorx.denominatorcomplex numbers noneuse Math::Complex;my $z = 1 + 1.414 * i;Re($z);Im($z);z = 1 + 1.414jz.realz.imagrequire 'complex'z = 1 + 1.414.imz.realz.imagrandom integer, uniform float, normal floatrand(0,99)lcg_value()noneint(rand() * 100)rand()noneimport randomrandom.randint(0,99)random.random()random.gauss(0,1)rand(100)randnoneset random seed, get and restore seedsrand(17);nonesrand 17;my $sd = srand;srand($sd);import randomrandom.seed(17)sd = random.getstate()random.setstate(sd)srand(17)sd = srandsrand(sd)bit operators > & | ^ ~> & | ^ ~> & | ^ ~> & | ^ ~binary, octal, and hex literalsnone0520x2a0b1010100520x2a0b1010100520x2a0b1010100520x2abase conversionbase_convert("42", 10, 7);base_convert("60", 7, 10);# cpan -i Math::BaseCalcuse Math::BaseCalc;$c = new Math::BaseCalc(digits=> [0..6]);$c->to_base(42);$c->from_base("60");noneint("60", 7)42.to_s(7)"60".to_i(7)strings phpperlpythonrubystring literal "don't say \"no\""'don\'t say "no"'"don't say \"no\""'don\'t say "no"''don\'t say "no"'"don't say \"no\"""don't " 'say "no"''''don't say "no"'''"""don't say "no\"""""don't say \"no\""'don\'t say "no"'"don't " 'say "no"'newline in literal yesyestriple quote literals onlyyesbackslash escapes double quoted:\f \n \r \t \v \xhh \$ \" \ooosingle quoted:\' \\double quoted:\a \b \cx \e \f \n \r \t \xhh \x{hhhh} \ooosingle quoted:\' \\single and double quoted:\newline \\ \' \" \a \b \f \n \r \t \v \ooo \xhhPython 3:\uhhhh \Uhhhhhhhhdouble quoted:\a \b \cx \e \f \n \r \s \t \v \xhh \oooRuby 1.9 double quoted:\uhhhh \u{hhhhh}single quoted:\' \\variable interpolation $count = 3;$item = "ball";echo "$count ${item}s\n";my $count = 3;my $item = "ball";print "$count ${item}s\n";count = 3item = 'ball'print('{count} {item}s'.format( **locals()))count = 3item = "ball"puts "#{count} #{item}s"custom delimitersnonemy $s1 = q(lorem ipsum);my $s2 = qq($s1 dolor sit amet);nones1 = %q(lorem ipsum)s2 = %Q(#{s1} dolor sit amet)sprintf $fmt = "lorem %s %d %f";sprintf($fmt, "ipsum", 13, 3.7);my $fmt = "lorem %s %d %f";sprintf($fmt, "ipsum", 13, 3.7)'lorem %s %d %f' % ('ipsum', 13, 3.7)fmt = 'lorem {0} {1} {2}'fmt.format('ipsum', 13, 3.7)"lorem %s %d %f" % ["ipsum",13,3.7]here document $word = "amet";$s = EOFlorem ipsumdolor sit $wordEOF;$word = "amet";$s = EOF;lorem ipsumdolor sit $wordEOFnoneword = "amet"s = EOFlorem ipsumdolor sit #{word}EOFconcatenate $s = "Hello, ";$s2 = $s . "World!";my $s = "Hello, ";my $s2 = $s . "World!";s = 'Hello, 's2 = s + 'World!'juxtaposition can be used to concatenate literals:s2 = 'Hello, ' "World!"s = "Hello, "s2 = s + "World!"juxtaposition can be used to concatenate literals:s2 ="Hello, " 'World!'replicate $hbar = str_repeat("-", 80);my $hbar = "-" x 80;hbar = '-' * 80hbar = "-" * 80split, in two, with delimiters, into charactersexplode(" ", "do re mi fa")preg_split('/\s+/', "do re mi fa", 2)preg_split('/(\s+)/', "do re mi fa", NULL, PREG_SPLIT_DELIM_CAPTURE);str_split("abcd")split(/\s+/, "do re mi fa")split(/\s+/, "do re mi fa", 2)split(/(\s+)/, "do re mi fa");split(//, "abcd")'do re mi fa'.split()'do re mi fa'.split(None, 1)re.split('(\s+)', 'do re mi fa')list('abcd')"do re mi fa".split"do re mi fa".split(/\s+/, 2)"do re mi fa".split(/(\s+)/)"abcd".split("")join $a = array("do", "re", "mi", "fa");implode(" ", $a)join(" ", qw(do re mi fa))' '.join(['do', 're', 'mi', 'fa'])%w(do re mi fa).join(' ')case manipulationstrtoupper("lorem")strtolower("LOREM")ucfirst("lorem")uc("lorem")lc("LOREM")ucfirst("lorem")'lorem'.upper()'LOREM'.lower()'lorem'.capitalize()"lorem".upcase"LOREM".downcase"lorem".capitalizestrip trim(" lorem ")ltrim(" lorem")rtrim("lorem ")# cpan -i Text::Trimuse Text::Trim;trim " lorem "ltrim " lorem"rtrim "lorem "' lorem '.strip()' lorem'.lstrip()'lorem '.rstrip()" lorem ".strip" lorem".lstrip"lorem ".rstrippad on right, on left str_pad("lorem", 10)str_pad("lorem", 10, " ", STR_PAD_LEFT)sprintf("%-10s", "lorem")sprintf("%10s", "lorem")'lorem'.ljust(10)'lorem'.rjust(10)"lorem".ljust(10)"lorem".rjust(10)length strlen("lorem")length("lorem")len('lorem')"lorem".length"lorem".sizeindex of substring strpos("do re re", "re")strrpos("do re re", "re")return FALSE if not foundindex("lorem ipsum", "ipsum")rindex("do re re", "re")return -1 if not found'do re re'.index('re')'do re re'.rindex('re')raise ValueError if not found"do re re".index("re")"do re re".rindex("re")return nil if not foundextract substring substr("lorem ipsum", 6, 5)substr("lorem ipsum", 6, 5)'lorem ipsum'[6:11]"lorem ipsum"[6, 5]extract charactersyntax error to use index notation directly on string literal:$s = "lorem ipsum";$s[6];can't use index notation with strings:substr("lorem ipsum", 6, 1)'lorem ipsum'[6]"lorem ipsum"[6]chr and ord chr(65)ord("A")chr(65)ord("A")chr(65)ord('A')65.chr"A"[0] Ruby 1.9: "A".ordcharacter translation $ins = implode(range("a", "z"));$outs = substr($ins, 13, 13) . substr($ins, 0, 13);strtr("hello", $ins, $outs)$s = "hello";$s =~ tr/a-z/n-za-m/;from string import lowercase as insfrom string import maketransouts = ins[13:] + ins[:13]'hello'.translate(maketrans(ins,outs))"hello".tr("a-z", "n-za-m")regular expresions phpperlpythonrubyliteral, custom delimited literal'/lorem|ipsum/''(/etc/hosts)'/lorem|ipsum/qr(/etc/hosts)re.compile('lorem|ipsum')none/lorem|ipsum/%r(/etc/hosts)character class abbreviations and anchorschar class abbrevs:. \d \D \h \H \s \S \v \V \w \Wanchors: ^ $ \A \b \B \z \Zchar class abbrevs:. \d \D \h \H \s \S \v \V \w \Wanchors: ^ $ \A \b \B \z \Zchar class abbrevs:. \d \D \s \S \w \Wanchors: ^ $ \A \b \B \Zchar class abbrevs:. \d \D \h \H \s \S \w \Wanchors: ^ $ \A \b \B \z \Zmatch test if (preg_match('/1999/', $s)) { echo "party!\n";}if ($s =~ /1999/) { print "party!\n";}if re.search('1999', s): print('party!')if /1999/.match(s) puts "party!"endcase insensitive match testpreg_match('/lorem/i', "Lorem")"Lorem" =~ /lorem/ire.search('lorem', 'Lorem', re.I)/lorem/i.match("Lorem")modifiers e i m s xi m s p xre.I re.M re.S re.Xi o m xsubstitution $s = "do re mi mi mi";$s = preg_replace('/mi/', "ma", $s);my $s = "do re mi mi mi";$s =~ s/mi/ma/g;s = 'do re mi mi mi's = re.compile('mi').sub('ma', s)s = "do re mi mi mi"s.gsub!(/mi/, "ma")match, prematch, postmatch noneif ($s =~ /\d{4}/p) { $match = ${^MATCH}; $prematch = ${^PREMATCH}; $postmatch = ${^POSTMATCH};}m = re.search('\d{4}', s)if m: match = m.group() prematch = s[0:m.start(0)] postmatch = s[m.end(0):len(s)]m = /\d{4}/.match(s)if m match = m[0] prematch = m.pre_match postmatch = m.post_matchendgroup capture $s = "2010-06-03";$rx = '/(\d{4})-(\d{2})-(\d{2})/';preg_match($rx, $s, $m);list($_, $yr, $mo, $dy) = $m;$rx = qr/(\d{4})-(\d{2})-(\d{2})/;"2010-06-03" =~ $rx;($yr, $mo, $dy) = ($1, $2, $3);rx = '(\d{4})-(\d{2})-(\d{2})'m = re.search(rx, '2010-06-03')yr, mo, dy = m.groups()rx = /(\d{4})-(\d{2})-(\d{2})/m = rx.match("2010-06-03")yr, mo, dy = m[1..3]scan $s = "dolor sit amet";preg_match_all('/\w+/', $s, $m);$a = $m[0];my $s = "dolor sit amet";@a = $s =~ m/\w+/g;s = 'dolor sit amet'a = re.findall('\w+', s)a = "dolor sit amet".scan(/\w+/)backreference in match and substitutionpreg_match('/(\w+) \1/', "do do")$s = "do re";$rx = '/(\w+) (\w+)/';$s = preg_replace($rx, '\2 \1', $s);"do do" =~ /(\w+) \1/my $s = "do re";$s =~ s/(\w+) (\w+)/$2 $1/;nonerx = re.compile('(\w+) (\w+)')rx.sub(r'\2 \1', 'do re')/(\w+) \1/.match("do do")"do re".sub(/(\w+) (\w+)/, '\2 \1')recursive regex'/\(([^()]*|($R))\)/'/\(([^()]*|(?R))\)/noneRuby 1.9:/(?\(([^()]*|\g)*\))/dates and time phpperlpythonrubydate/time type DateTimeTime::Piece if use Time::Piece in effect, otherwise tm arraydatetime.datetimeTimecurrent date/time$t = new DateTime("now");$utc_tmz = new DateTimeZone("UTC");$utc = new DateTime("now", $utc_tmz);use Time::Piece;my $t = localtime(time);my $utc = gmtime(time);import datetimet = datetime.datetime.now()utc = datetime.datetime.utcnow()t = Time.nowutc = Time.now.utcto unix epoch, from unix epoch$epoch = $t->getTimestamp();$t2 = new DateTime();$t2->setTimestamp(1304442000);use Time::Local;use Time::Piece;my $epoch = timelocal($t);my $t2 = localtime(1304442000);from datetime import datetime as dtepoch = int(t.strftime("%s"))t2 = dt.fromtimestamp(1304442000)epoch = t.to_it2 = Time.at(1304442000)current unix epoch$epoch = time();$epoch = time;import datetimet = datetime.datetime.now()epoch = int(t.strftime("%s"))epoch = Time.now.to_istrftimestrftime("%Y-%m-%d %H:%M:%S", $epoch);date("Y-m-d H:i:s", $epoch);$t->format("Y-m-d H:i:s");use Time::Piece;$t = localtime(time);$fmt = "%Y-%m-%d %H:%M:%S";print $t->strftime($fmt);t.strftime('%Y-%m-%d %H:%M:%S')t.strftime("%Y-%m-%d %H:%M:%S")default format exampleno default string representationTue Aug 23 19:35:19 20112011-08-23 19:35:59.4111352011-08-23 17:44:53 -0700strptime$fmt = "Y-m-d H:i:s";$s = "2011-05-03 10:00:00";$t = DateTime::createFromFormat($fmt, $s);use Time::Local;use Time::Piece;$s = "2011-05-03 10:00:00";$fmt = "%Y-%m-%d %H:%M:%S";$t = Time::Piece->strptime($s,$fmt);from datetime import datetimes = '2011-05-03 10:00:00'fmt = '%Y-%m-%d %H:%M:%S't = datetime.strptime(s, fmt)require 'date's = "2011-05-03 10:00:00"fmt = "%Y-%m-%d %H:%M:%S"t = Date.strptime(s, fmt).to_timeparse date w/o format$epoch = strtotime("July 7, 1999");# cpan -i Date::Parseuse Date::Parse;$epoch = str2time("July 7, 1999");# pip install python-dateutilimport dateutil.parsers = 'July 7, 1999't = dateutil.parser.parse(s)require 'date's = "July 7, 1999"t = Date.parse(s).to_timeresult of date subtractionDateInterval object if diff method used:$fmt = "Y-m-d H:i:s";$s = "2011-05-03 10:00:00";$then = DateTime::createFromFormat($fmt, $s);$now = new DateTime("now");$interval = $now->diff($then);Time::Seconds object if use Time::Piece in effect; not meaningful to subtract tm arraysdatetime.timedelta objectFloat containing time difference in secondsadd time duration$now = new DateTime("now");$now->add(new DateInterval("PT10M3S");use Time::Seconds;$now = localtime(time);$now += 10 * ONE_MINUTE() + 3;import datetimedelta = datetime.timedelta( minutes=10, seconds=3)t = datetime.datetime.now() + deltarequire 'date/delta's = "10 min, 3 s"delta = Date::Delta.parse(s).in_secst = Time.now + deltalocal timezoneDateTime objects can be instantiated without specifying the timezone if a default is set:$s = "America/Los_Angeles";date_default_timezone_set($s);Time::Piece has local timezone if created with localtimeand UTC timezone if created with gmtime; tm arrays have no timezone or offset infoa datetime object has no timezone information unless atzinfo object is provided when it is createdif no timezone is specified the local timezone is usedtimezone name; offset from UTC; is daylight savings?$tmz = date_timezone_get($t);timezone_name_get($tmz);date_offset_get($t) / 3600;$t->format("I");# cpan -i DateTimeuse DateTime;use DateTime::TimeZone;$dt = DateTime->now();$tz = DateTime::TimeZone->new( name=>"local");$tz->name;$tz->offset_for_datetime($dt) / 3600;$tz->is_dst_for_datetime($dt);import timetm = time.localtime() time.tzname[tm.tm_isdst](time.timezone / -3600) + tm.tm_isdsttm.tm_isdstt.zonet.utc_offset / 3600t.dst?microsecondslist($frac, $sec) = explode(" ", microtime());$usec = $frac * 1000 * 1000;use Time::HiRes qw(gettimeofday);($sec, $usec) = gettimeofday;t.microsecondt.usecsleepa float argument will be truncated to an integer:sleep(1);a float argument will be truncated to an integer:sleep 1;import timetime.sleep(0.5)sleep(0.5)timeoutuse set_time_limit to limit execution time of the entire script; use stream_set_timeout to limit time spent reading from a stream opened with fopen or fsockopeneval { $SIG{ALRM}= sub {die "timeout!";}; alarm 5; sleep 10;};alarm 0;import signal, timeclass Timeout(Exception): passdef timeout_handler(signo, fm): raise Timeout()signal.signal(signal.SIGALRM, timeout_handler)try: signal.alarm(5) time.sleep(10)except Timeout: passsignal.alarm(0)require 'timeout'begin Timeout.timeout(5) do sleep(10) endrescue Timeout::Errorendarrays phpperlpythonrubyliteral $a = array(1, 2, 3, 4);@a = (1, 2, 3, 4);a = [1, 2, 3, 4]a = [1, 2, 3, 4]quote words none@a = qw(do re mi);nonea = %w(do re mi)size count($a)$#a + 1 orscalar(@a)len(a)a.sizea.length # same as sizeempty test !$a!@anot aNoMethodError if a is nil:a.empty?lookup $a[0]$a[0]a[0]a[0]update $a[0] = "lorem";$a[0] = "lorem";a[0] = 'lorem'a[0] = "lorem"out-of-bounds behavior$a = array();evaluates as NULL:$a[10];increases array size to one:$a[10] = "lorem";@a = ();evaluates as undef:$a[10];increases array size to 11:$a[10] = "lorem";a = []raises IndexError:a[10]raises IndexError:a[10] = 'lorem'a = []evaluates as nil:a[10]increases array size to 11:a[10] = "lorem"index of array element$a = array("x", "y", "z", "w");$i = array_search("y", $a);use List::Util 'first';@a = qw(x y z w);$i = first {$a[$_] eq "y"} (0..$#a);a = ['x', 'y', 'z', 'w']i = a.index('y')a = %w(x y z w)i = a.index("y")slice by endpoints, by length select 3rd and 4th elements:nonearray_slice($a, 2, 2)select 3rd and 4th elements:@a[2..3]splice(@a, 2, 2)select 3rd and 4th elements:a[2:4]noneselect 3rd and 4th elements:a[2..3]a[2, 2]slice to end array_slice($a, 1)@a[1..$#a]a[1:]a[1..-1]manipulate back $a = array(6,7,8);array_push($a, 9);$a[] = 9; # same as array_pusharray_pop($a);@a = (6,7,8);push @a, 9;pop @a;a = [6,7,8]a.append(9)a.pop()a = [6,7,8]a.push(9)a 9 # same as pusha.popmanipulate front $a = array(6,7,8);array_unshift($a, 5);array_shift($a);@a = (6,7,8);unshift @a, 5;shift @a;a = [6,7,8]a.insert(0,5)a.pop(0)a = [6,7,8]a.unshift(5)a.shiftconcatenate$a = array(1,2,3);$a2 = array_merge($a,array(4,5,6));$a = array_merge($a,array(4,5,6));@a = (1,2,3);@a2 = (@a,(4,5,6));push @a, (4,5,6);a = [1,2,3]a2 = a + [4,5,6]a.extend([4,5,6])a = [1,2,3]a2 = a + [4,5,6]a.concat([4,5,6])replicate @a = (undef) x 10;a = [None] * 10a = [None for i in range(0, 10)]a = [nil] * 10a = Array.new(10, nil)address copy, shallow copy, deep copy$a = array(1,2,array(3,4));$a2 =& $a;none$a4 = $a;use Storable 'dclone'my @a = (1,2,[3,4]);my $a2 = \@a;my @a3 = @a;my @a4 = @{dclone(\@a)};import copya = [1,2,[3,4]]a2 = aa3 = list(a)a4 = copy.deepcopy(a)a = [1,2,[3,4]]a2 = aa3 = a.dupa4 = Marshal.load(Marshal.dump(a))arrays as function argumentsparameter contains deep copyeach element passed as separate argument; use reference to pass array as single argumentparameter contains address copyparameter contains address copyiteration foreach (array(1,2,3) as $i) { echo "$i\n";}for $i (1, 2, 3) { print "$i\n" }for i in [1,2,3]: print(i)[1,2,3].each { |i| puts i }indexed iteration$a = array("do", "re", "mi" "fa");foreach ($a as $i => $s) { echo "$s at index $i\n";}none; use range iteration from 0 to $#a and use index to look up value in the loop bodya = ['do', 're', 'mi', 'fa']for i, s in enumerate(a): print('%s at index %d' % (s, i))a = %w(do re mi fa)a.each_with_index do |s,i| puts "#{s} at index #{i}"enditerate over rangenot space efficient; use C-style for loopfor $i (1..1_000_000) { code}range replaces xrange in Python 3:for i in xrange(1, 1000001): code(1..1_000_000).each do |i| codeendinstantiate range as array$a = range(1, 10);@a = 1..10;a = range(1, 11)Python 3:a = list(range(1, 11))a = (1..10).to_areverse$a = array(1,2,3);array_reverse($a);$a = array_reverse($a);@a = (1,2,3);reverse @a;@a = reverse @a;a = [1,2,3]a[::-1]a.reverse()a = [1,2,3]a.reversea.reverse!sort$a = array("b", "A", "a", "B");nonesort($a);none, but usort sorts in place@a = qw(b A a B);sort @a;@a = sort @a;sort { lc($a) cmp lc($b) } @a;a = ['b', 'A', 'a', 'B']sorted(a)a.sort()a.sort(key=str.lower)a = %w(b A a B)a.sorta.sort!a.sort do |x,y| x.downcase y.downcaseenddedupe$a = array(1,2,2,3);$a2 = array_unique($a);$a = array_unique($a);use List::MoreUtils 'uniq';my @a = (1,2,2,3);my @a2 = uniq @a;@a = uniq @a;a = [1,2,2,3]a2 = list(set(a))a = list(set(a))a = [1,2,2,3]a2 = a.uniqa.uniq!membership in_array(7, $a)7 ~~ @a7 in aa.include?(7)interdiv $a = array(1,2);$b = array(2,3,4)array_intersect($a, $b) {1,2} & {2,3,4}[1,2] & [2,3,4]union $a1 = array(1,2);$a2 = array(2,3,4);array_unique(array_merge($a1, $a2)) {1,2} | {2,3,4}[1,2] | [2,3,4]relative complement, symmetric difference$a1 = array(1,2,3);$a2 = array(2);array_values(array_diff($a1, $a2))none {1,2,3} - {2}{1,2} ^ {2,3,4}require 'set'[1,2,3] - [2]Set[1,2] ^ Set[2,3,4]map array_map(function ($x) { return $x*$x; }, array(1,2,3))map { $_ * $_ } (1,2,3)map(lambda x: x * x, [1,2,3])# or use list comprehension:[x*x for x in [1,2,3]][1,2,3].map { |
08-28 02:39