讲师中心 微信公众号
AI工具推荐 视频效率加速

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

千浩酱_6432

千浩酱_6432

发布时间:2016-06-06 19:59:27

|

2348人浏览过

|

来源于php中文网

原创

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

Shadows Python Sensei
Shadows Python Sensei

Python 最佳实践助手——代码规范、设计模式、性能优化、测试与类型注解。适用于编写或审查 Python 代码。

下载

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 ";' $ perl -e 'print("hi ")' $ 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:
xhh $ " ooo

single quoted:
' \
double quoted:
  cx e xhh x{hhhh} ooo

single quoted:
' \
single and double quoted:
newline \ ' "   ooo xhh

Python 3:
uhhhh Uhhhhhhhh
double quoted:
  cx e s xhh ooo

Ruby 1.9 double quoted:
uhhhh u{hhhhh}

single quoted:
' \
variable interpolation
 
$count = 3;
$item = "ball";
echo "$count ${item}s ";
my $count = 3;
my $item = "ball";
print "$count ${item}s ";
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 w W

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

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

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

anchors: ^ $ A  B z Z
match test
 
if (preg_match('/1999/', $s)) {
  echo "party! ";
}
if ($s =~ /1999/) {
  print "party! ";
}
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+) /'"do do")

$s = "do re";
$rx = '/(w+) (w+)/';
$s = preg_replace($rx' ', $s);
"do do" =~ /(w+) /

my $s = "do re";
$s =~ s/(w+) (w+)/$2 $1/;
none

rx = re.compile('(w+) (w+)')
rx.sub(r' ''do re')
/(w+) /.match("do do")

"do re".sub(/(w+) (w+)/' ')
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 ";
}
for $i (1, 2, 3) { print "$i " } 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 ";
}
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 { |

相关文章

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

切问学术

切问学术是一款AI论文写作工具,复旦大学NLP团队推出的AI学术智能体。

超级简历WonderCV

一款AI办公效率工具,主要用于免费求职简历模版下载制作,应届生职场人必备简历制作神器,适合需要提升相关任务效率的用户。

二狗PPT
二狗PPT Hot

一款AI演示文稿工具,主要用于专为中式职场打造的AI PPT生成工具,适合需要提升相关任务效率的用户。

Laper
Laper Hot

Laper是专为编剧、导演和制片人推出的 AI 原生剧本创作工具。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

墨刀AI
墨刀AI Hot

一款AI图像与设计工具,主要用于产品经理的专属智能体,适合需要提升相关任务效率的用户。

AionClaw
AionClaw Hot

AionClaw是一款面向办公、创作和编程任务的AI桌面智能体。

相关专题

更多
Vibeknow在线使用入口合集
Vibeknow在线使用入口合集

本专题汇总了Vibeknow在线创作视频的官方入口及网页版使用教程,涵盖PPT、PDF、Word等文档一键转讲解视频的核心操作,并整理了免费版水印规则与手机端浏览器访问指南,助你快速将知识内容视频化。

20

2026.09.21

NumPy随机数文件读写与dtype数据类型
NumPy随机数文件读写与dtype数据类型

本专题整理 NumPy 随机数、文件读写与 dtype 数据类型相关教程,覆盖 Generator/random、随机数种子、正态分布采样、npy/npz/CSV/TXT 保存读取、loadtxt/savetxt、memmap、大文件处理、astype 类型转换、结构化 dtype、整数溢出和精度丢失等场景。

0

2026.09.21

NumPy矩阵运算与线性代数计算
NumPy矩阵运算与线性代数计算

本专题整理 NumPy 矩阵运算与线性代数计算相关教程,覆盖矩阵乘法、dot 与 @ 运算符、逆矩阵、行列式、特征值与特征向量、SVD、线性方程组、欧氏距离、矩阵分解和大规模矩阵性能优化等内容,帮助读者掌握 np.linalg 与矩阵计算实战。

0

2026.09.21

NumPy广播机制数学运算与统计分析
NumPy广播机制数学运算与统计分析

本专题整理 NumPy 广播机制、数组数学运算与统计分析相关教程,覆盖广播规则、维度对齐、矩阵与数组加减除法、向量化计算、均值方差、分位数、中位数、直方图和 unique 频次统计等场景,帮助读者掌握 ndarray 高效计算与统计处理方法。

0

2026.09.21

NumPy数组创建索引切片与数据选择
NumPy数组创建索引切片与数据选择

本专题整理 NumPy 数组创建、索引、切片与数据选择相关教程,覆盖 np.array、zeros/ones、多维数组形状、基础切片、花式索引、布尔索引、条件筛选、视图与副本等常用场景,帮助读者系统掌握 ndarray 数据构造与高效提取方法。

0

2026.09.21

Aionclaw智能助手介绍
Aionclaw智能助手介绍

本专题汇总了AionClaw(AI龙虾助手)的功能介绍与在线使用入口。AionClaw是杭州趣猿人工智能有限公司推出的桌面级AI智能体,能直接在电脑上读写文件、运行脚本、操作浏览器,自动交付Word、PPT、Excel等成品。

40

2026.09.20

AionClaw AI智能体与电脑自动化任务执行功能使用教程
AionClaw AI智能体与电脑自动化任务执行功能使用教程

AionClaw专题整理AI智能体与电脑自动化相关功能使用教程,涵盖安装部署、AI任务执行、Skills技能、文件处理、浏览器控制、电脑操作、持久记忆、聊天工具连接以及办公、编程和内容创作等功能,帮助用户快速掌握AionClaw的实际使用方法。

0

2026.09.20

AI视频生成软件推荐
AI视频生成软件推荐

本专题汇总了当前主流的AI视频生成软件推荐与排行榜单,涵盖seko、AniShort、剧云、Lovart、LiblibAI及立刻mv等热门工具。同时整理了各软件在文生视频、图生视频、时长限制、画质表现及免费额度等方面的差异对比,助您快速选对适合创作需求的AI视频生成工具。

200

2026.09.16

ai生成视频的工具免费版合集
ai生成视频的工具免费版合集

本专题汇总了当前免费AI生成视频工具的排行榜与推荐清单,涵盖seko、讯飞智作、AniShort及剧云、Lovart等多模型集成平台。同时整理了各工具的免费额度、输出时长、水印政策及适用场景差异,助您快速选择合适工具开启AI视频创作。

100

2026.09.16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
墨刀帮助中心
墨刀帮助中心

共0课时 | 0人学习

MyEclipse学习中心
MyEclipse学习中心

共0课时 | 0人学习

Apache Subversion 官方手册
Apache Subversion 官方手册

共0课时 | 0人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn