首頁 >php教程 >php手册 >PHP, Perl, Python, Ruby 语言特性的区别

PHP, Perl, Python, Ruby 语言特性的区别

WBOY
WBOY原創
2016-06-06 19:59:272006瀏覽

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 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 | tests | debugging and profiling | java interop | contact

php (1995) perl (1987) python (1991) ruby (1995)
versions used
 
5.3 5.12; 5.14 2.7; 3.2 1.8; 1.9
implicit prologue none use strict; import os, re, sys none
show version
 
$ php --version $ perl --version $ python -V $ ruby --version
interpreter
 
$ php -f foo.php $ perl foo.pl $ python foo.py $ ruby foo.rb
repl
 
$ php $ perl -de 0 $ python $ irb
command 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 end
assignment
 
$v = 1; $v = 1; assignments can be chained but otherwise don't return values:
v = 1
v = 1
parallel 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);
xyz = 1, 2, 3
# raises ValueError:
xy = 1, 2, 3
# raises ValueError:
xyz = 1, 2
x, y, z = 1, 2, 3
# 3 is discarded:
x, y = 1, 2, 3
# z set to nil:
x, y, z = 1, 2
swap
 
list($x, $y) = array($y, $x); ($x, $y) = ($y, $x); xy = y, x x, y = y, x
compound 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;
none x = 1
# x and y not mutated:
y = x.succ
z = y.pred
local 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 = None
ad = [], {}
x = 1
yz = 2, 3
v = nil
a, d = [], {}
x = 1
y, z = 2, 3
regions which define local scope top level:
  function or method body

nestable (with use clause):
  anonymous function body
top level:
  file

nestable:
  function body
  anonymous function body
  anonymous block
nestable (read only):
  function or method body
top level:
  file
  class block
  module block
  method body

nestable:
  anonymous function block
  anonymous block
global variable list($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);
}
g1g2 = 7, 8
def swap_globals():
  global g1, g2
  g1, g2 = g2, g1
$g1$g2 = 7, 8
def swap_globals
  $g1$g2 = $g2$g1
end
constant declaration
 
define("PI", 3.14); use constant PI => 3.14; # uppercase identifiers
# constant by convention

PI = 3.14
# warning if capitalized
# identifier is reassigned

PI = 3.14
to-end-of-line comment
 
// comment
# comment
# comment # comment # comment
comment out multiple lines
 
/* comment line
another line */
=for
comment line
another line
=cut
use triple quote string literal:
'''comment line
another line'''
=begin
comment line
another line
=end
null
 
NULL # case insensitive undef None nil
null test
 
is_null($v)
! isset($v)
defined $v v == None
is None
v == nil
v.nil?
undefined variable access
 
NULL error under use strict; otherwise undef raises NameError raises NameError
undefined test
 
same as null test; no distinction between undefined variables and variables set to NULL same as null test; no distinction between undefined variables and variables set to undef not_defined = False
try: v
except NameError: not_defined = True
defined?(v)
arithmetic and logic
  php perl python ruby
true and false
 
TRUE FALSE # case insensitve "" True False true false
falsehoods
 
FALSE NULL 0 0.0 "" "0" array() undef 0 0.0 "" "0" () False None 0 0.0 '' [] {} false nil
logical operators
 
&& || !
lower precedence:
and or xor
&& || !
lower precedence:
and or xor not
and or not && || !
lower precedence:
and or not
conditional expression
 
$x > 0 ? $x : -$x $x > 0 ? $x : -$x if x > 0 else -x x > 0 ? x : -x
comparison operators
 
== != or  > = no conversion: === !== numbers only: == != > = strings: eq ne gt lt ge le comparison operators are chainable:
== != > =
== != > =
three value comparison none 0 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: " . 8
7 + "12"
73.9 + ".037"
"value: " . 8
7 + int('12')
73.9 + float('.037')
'value: ' + str(8)
7 + "12".to_i
73.9 + ".037".to_f
"value: " + "8".to_s
arithmetic operators
 
+ - * / none % pow(b,e) + - * / none % ** + - * / // % ** + - * x.fdiv(y) / % **
integer division and divmod
 
(int) (13 / 5)
none
int ( 13 / 5 )
none
13 // 5
q, r = divmod(13, 5)
13 / 5
q, r = 13.divmod(5)
float division
 
13 / 5 13 / 5 float(13) / 5
# Python 3:
13 / 5
13.to_f / 5 or
13.fdiv(5)
arithmetic functions
 
sqrt exp log sin cos tan asin acos atan atan2 use Math::Trig qw(
  tan asin acos atan);

sqrt exp log sin cos tan asin acos atan atan2
from math import sqrt, exp, log, \
sin, cos, tan, asin, acos, atan, atan2
include Math

sqrt exp log sin cos tan asin acos atan atan2
arithmetic truncation
 
(int)$x
round($x)
ceil($x)
floor($x)
abs($x)
# cpan -i Number::Format
use Number::Format 'round';
use POSIX qw(ceil floor);

int($x)
round($x, 0)
ceil($x)
floor($x)
abs($x)
import math

int(x)
int(round(x))
math.ceil(x)
math.floor(x)
abs(x)
x.to_i
x.round
x.ceil
x.floor
x.abs
min 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].max
division by zero
 
returns FALSE with warning error raises ZeroDivisionError integer division raises ZeroDivisionError
float division returns Infinity
integer overflow
 
converted to float converted to float; use Math::BigInt to create arbitrary length integers becomes arbitrary length integer of type long becomes arbitrary length integer of type Bignum
float overflow
 
INF inf raises OverflowError Infinity
sqrt -2
 
NaN error unless use Math::Complex in effect # raises ValueError:
import math
math.sqrt(-2)

# returns complex float:
import cmath
cmath.sqrt(-2)
raises Errno::EDOM
rational numbers
 
none use Math::BigRat;

my $x = Math::BigRat->new("22/7");
$x->numerator();
$x->denominator();
from fractions import Fraction

x = Fraction(22,7)
x.numerator
x.denominator
require 'rational'

x = Rational(22,7)
x.numerator
x.denominator
complex numbers
 
none use Math::Complex;

my $z = 1 + 1.414 * i;
Re($z);
Im($z);
z = 1 + 1.414j
z.real
z.imag
require 'complex'

z = 1 + 1.414.im
z.real
z.imag
random integer, uniform float, normal float rand(0,99)
lcg_value()
none
int(rand() * 100)
rand()
none
import random

random.randint(0,99)
random.random()
random.gauss(0,1)
rand(100)
rand
none
set random seed, get and restore seed srand(17);

none
srand 17;

my $sd = srand;
srand($sd);
import random

random.seed(17)
sd = random.getstate()
random.setstate(sd)
srand(17)

sd = srand
srand(sd)
bit operators
 
> & | ^ ~ > & | ^ ~ > & | ^ ~ > & | ^ ~
binary, octal, and hex literals none
052
0x2a
0b101010
052
0x2a
0b101010
052
0x2a
0b101010
052
0x2a
base conversion base_convert("42", 10, 7);
base_convert("60", 7, 10);
# cpan -i Math::BaseCalc
use Math::BaseCalc;

$c = new Math::BaseCalc(digits=>
  [0..6]);
$c->to_base(42);
$c->from_base("60");
none
int("60", 7)
42.to_s(7)
"60".to_i(7)
strings
  php perl python ruby
string 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
 
yes yes triple quote literals only yes
backslash escapes
 
double quoted:
\f \n \r \t \v \xhh \$ \" \ooo

single quoted:
\' \\
double quoted:
\a \b \cx \e \f \n \r \t \xhh \x{hhhh} \ooo

single quoted:
\' \\
single and double quoted:
\newline \\ \' \" \a \b \f \n \r \t \v \ooo \xhh

Python 3:
\uhhhh \Uhhhhhhhh
double quoted:
\a \b \cx \e \f \n \r \s \t \v \xhh \ooo

Ruby 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 = 3
item = 'ball'
print('{count} {item}s'.format(
  **locals()))
count = 3
item = "ball"
puts "#{count} #{item}s"
custom delimiters none my $s1 = q(lorem ipsum);
my $s2 = qq($s1 dolor sit amet);
none s1 = %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 = EOF
lorem ipsum
dolor sit $word
EOF
;
$word = "amet";
$s = EOF;
lorem ipsum
dolor sit $word

EOF
none word = "amet"
s = EOF
lorem ipsum
dolor sit
 #{word}
EOF
concatenate
 
$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 = '-' * 80 hbar = "-" * 80
split, in two, with delimiters, into characters explode(" ""do re mi fa")
preg_split('/\s+/'"do re mi fa", 2)
preg_split('/(\s+)/'"do re mi fa",
  NULLPREG_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 manipulation strtoupper("lorem")
strtolower("LOREM")
ucfirst("lorem")
uc("lorem")
lc("LOREM")
ucfirst("lorem")
'lorem'.upper()
'LOREM'.lower()
'lorem'.capitalize()
"lorem".upcase
"LOREM".downcase
"lorem".capitalize
strip
 
trim(" lorem ")
ltrim(" lorem")
rtrim("lorem ")
# cpan -i Text::Trim
use Text::Trim;

trim " lorem "
ltrim " lorem"
rtrim "lorem "
' lorem '.strip()
' lorem'.lstrip()
'lorem '.rstrip()
" lorem ".strip
" lorem".lstrip
"lorem ".rstrip
pad 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".size
index of substring
 
strpos("do re re""re")
strrpos("do re re""re")
return FALSE if not found
index("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 found
extract substring
 
substr("lorem ipsum", 6, 5) substr("lorem ipsum", 6, 5) 'lorem ipsum'[6:11] "lorem ipsum"[6, 5]
extract character syntax 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".ord
character 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 ins
from string import maketrans

outs = ins[13:] + ins[:13]
'hello'.translate(maketrans(ins,outs))
"hello".tr("a-z""n-za-m")
regular expresions
  php perl python ruby
literal, 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 anchors char class abbrevs:
. \d \D \h \H \s \S \v \V \w \W

anchors: ^ $ \A \b \B \z \Z
char class abbrevs:
. \d \D \h \H \s \S \v \V \w \W

anchors: ^ $ \A \b \B \z \Z
char class abbrevs:
. \d \D \s \S \w \W

anchors: ^ $ \A \b \B \Z
char class abbrevs:
. \d \D \h \H \s \S \w \W

anchors: ^ $ \A \b \B \z \Z
match 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!"
end
case insensitive match test preg_match('/lorem/i'"Lorem") "Lorem" =~ /lorem/i re.search('lorem''Lorem', re.I) /lorem/i.match("Lorem")
modifiers
 
e i m s x i m s p x re.I re.M re.S re.X i o m x
substitution
 
$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
 
none if ($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_match
end
group 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')
yrmody = 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 substitution preg_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/;
none

rx = 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))\)/ none Ruby 1.9:
/(?

\(([^()]*|\g

)*\))/

dates and time
  php perl python ruby
date/time type
 
DateTime Time::Piece if use Time::Piece in effect, otherwise tm array datetime.datetime Time
current 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 datetime

t = datetime.datetime.now()
utc = datetime.datetime.utcnow()
t = Time.now
utc = Time.now.utc
to 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 dt

epoch = int(t.strftime("%s"))
t2 = dt.fromtimestamp(1304442000)
epoch = t.to_i
t2 = Time.at(1304442000)
current unix epoch $epoch = time(); $epoch = time; import datetime

t = datetime.datetime.now()
epoch = int(t.strftime("%s"))
epoch = Time.now.to_i
strftime strftime("%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 example no default string representation Tue Aug 23 19:35:19 2011 2011-08-23 19:35:59.411135 2011-08-23 17:44:53 -0700
strptime $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 datetime

s = '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_time
parse date w/o format $epoch = strtotime("July 7, 1999"); # cpan -i Date::Parse
use Date::Parse;

$epoch = str2time("July 7, 1999");
# pip install python-dateutil
import dateutil.parser

s = 'July 7, 1999'
t = dateutil.parser.parse(s)
require 'date'

s = "July 7, 1999"
t = Date.parse(s).to_time
result of date subtraction DateInterval 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 arrays datetime.timedelta object Float containing time difference in seconds
add time duration $now = new DateTime("now");
$now->add(new DateInterval("PT10M3S");
use Time::Seconds;

$now = localtime(time);
$now += 10 * ONE_MINUTE() + 3;
import datetime

delta = datetime.timedelta(
  minutes=10,
  seconds=3)
t = datetime.datetime.now() + delta
require 'date/delta'

s = "10 min, 3 s"
delta = Date::Delta.parse(s).in_secs
t = Time.now + delta
local timezone DateTime 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 info a datetime object has no timezone information unless atzinfo object is provided when it is created if no timezone is specified the local timezone is used
timezone 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 DateTime
use 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 time

tm = time.localtime()
  
time.tzname[tm.tm_isdst]
(time.timezone / -3600) + tm.tm_isdst
tm.tm_isdst
t.zone
t.utc_offset / 3600
t.dst?
microseconds list($frac, $sec) = explode(" ",
  microtime());
$usec = $frac * 1000 * 1000;
use Time::HiRes qw(gettimeofday);

($sec, $usec) = gettimeofday;
t.microsecond t.usec
sleep a float argument will be truncated to an integer:
sleep(1);
a float argument will be truncated to an integer:
sleep 1;
import time

time.sleep(0.5)
sleep(0.5)
timeout use 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 fsockopen eval {
  $SIG{ALRM}= sub {die "timeout!";};
  alarm 5;
  sleep 10;
};
alarm 0;
import signal, time

class Timeout(Exception): pass

def timeout_handler(signo, fm):
  raise Timeout()

signal.signal(signal.SIGALRM,
  timeout_handler)

try:
  signal.alarm(5)
  time.sleep(10)
except Timeout:
  pass
signal.alarm(0)
require 'timeout'

begin
  Timeout.timeout(5) do
    sleep(10)
  end
rescue Timeout::Error
end
arrays
  php perl python ruby
literal
 
$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); none a = %w(do re mi)
size
 
count($a) $#a + 1 or
scalar(@a)
len(a) a.size
a.length # same as size
empty test
 
!$a !@a not a NoMethodError 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:
none
array_slice($a, 2, 2)
select 3rd and 4th elements:
@a[2..3]
splice(@a, 2, 2)
select 3rd and 4th elements:
a[2:4]
none
select 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_push
array_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)
 9 # same as push
a.pop
manipulate 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.shift
concatenate $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 = (undefx 10; a = [None] * 10
a = [None for i in range(0, 10)]
a = [nil] * 10
a = 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 copy

a = [1,2,[3,4]]
a2 = a
a3 = list(a)
a4 = copy.deepcopy(a)
a = [1,2,[3,4]]
a2 = a
a3 = a.dup
a4 = Marshal.load(Marshal.dump(a))
arrays as function arguments parameter contains deep copy each element passed as separate argument; use reference to pass array as single argument parameter contains address copy parameter contains address copy
iteration
 
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 body a = ['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}"
end
iterate over range not space efficient; use C-style for loop for $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|
  code
end
instantiate 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_a
reverse $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.reverse
a.reverse!
sort $a = array("b""A""a""B");
none
sort($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.sort
a.sort!
a.sort do |x,y|
  x.downcase y.downcase
end
dedupe $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.uniq
a.uniq!
membership
 
in_array(7, $a) 7 ~~ @a in a a.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 { |
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn