700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > PHP Perl Python Ruby 语言特性的区别

PHP Perl Python Ruby 语言特性的区别

时间:2022-03-01 09:55:44

相关推荐

PHP  Perl  Python  Ruby 语言特性的区别

php教程|php手册

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

php教程-php手册

java门户网站模板源码,vscode+js文件提示,ubuntu sh指令,tomcat管理无法进入,怎么煎爬虫,php中查询数据库,广州seo方案优化费用,家具定制网网站源码,直销系统模板lzw

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

cep 源码,ubuntu 安装完成,安居客 python爬虫,lockex php,seo工具总部lzw

安卓仿微信源码,ubuntu复制系统文件,云南爬爬虫学名,.php加密,快照seo服务lzw

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 used5.35.12; 5.142.7; 3.21.8; 1.9
implicit prologuenoneuse strict;import os, re, sysnone
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 assignmentlist($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, 2

x, y, z = 1, 2, 3

# 3 is discarded:

x, y = 1, 2, 3

# z set to nil:

x, y, z = 1, 2

swaplist($x, $y) = array($y, $x);($x, $y) = ($y, $x);x, y = y, xx, 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;

nonex = 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

a, d = [], {}

x = 1

y, z = 2, 3

v = nil

a, d = [], {}

x = 1

y, z = 2, 3

regions which define local scopetop 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 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, 8

def swap_globals():

global g1, g2

g1, g2 = g2, g1

$g1, $g2 = 7, 8

def swap_globals

$g1, $g2 = $g2, $g1

end

constant declarationdefine(“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

nullNULL # case insensitiveundefNonenil
null testis_null($v)

! isset($v)

! defined $vv == None

v is None

v == nil

v.nil?

undefined variable accessNULLerror under use strict; otherwise undefraises NameErrorraises NameError
undefined testsame 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 = False

try: v

except NameError: not_defined = True

! defined?(v)
arithmetic and logic
phpperlpythonruby
true and falseTRUE FALSE # case insensitve1 “”True Falsetrue false
falsehoodsFALSE 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 : -$xx if x > 0 else -xx > 0 ? x : -x
comparison operators== != or > = <=

no conversion: === !==

numbers only: == != > = <=

strings: eq ne gt lt ge le

comparison 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 string7 + “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 division13 / 513 / 5float(13) / 5

# Python 3:

13 / 5

13.to_f / 5 or

13.fdiv(5)

arithmetic functionssqrt 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 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 maxmin(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 zeroreturns FALSE with warningerrorraises ZeroDivisionErrorinteger division raises ZeroDivisionError

float division returns Infinity

integer overflowconverted to floatconverted to float; use Math::BigInt to create arbitrary length integersbecomes arbitrary length integer of type longbecomes arbitrary length integer of type Bignum
float overflowINFinfraises OverflowErrorInfinity
sqrt -2NaNerror 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 numbersnoneuse 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 numbersnoneuse 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 floatrand(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 seedsrand(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 literalsnone

052

0x2a

0b101010

052

0x2a

0b101010

052

0x2a

0b101010

052

0x2a

base conversionbase_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
phpperlpythonruby
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 literalyesyestriple quote literals onlyyes
backslash escapesdouble 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 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 = <<<EOF

lorem ipsum

dolor sit $word

EOF;

$word = “amet”;

$s = <<EOF;

lorem ipsum

dolor sit $word

EOF

noneword = “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 = ‘-‘ * 80hbar = “-” * 80
split, 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”.capitalize

striptrim(” 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 leftstr_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)

lengthstrlen(“lorem”)length(“lorem”)len(‘lorem’)“lorem”.length

“lorem”.size

index of substringstrpos(“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 substringsubstr(“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 ordchr(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
phpperlpythonruby
literal, custom delimited literal‘/lorem|ipsum/’

‘(/etc/hosts)’

/lorem|ipsum/

qr(/etc/hosts)

pile(‘lorem|ipsum’)

none

/lorem|ipsum/

%r(/etc/hosts)

character class abbreviations and anchorschar 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 testif (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 testpreg_match(‘/lorem/i’, “Lorem”)“Lorem” =~ /lorem/ire.search(‘lorem’, ‘Lorem’, re.I)/lorem/i.match(“Lorem”)
modifierse i m s xi m s p xre.I re.M re.S re.Xi 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 = pile(‘mi’).sub(‘ma’, s)

s = “do re mi mi mi”

s.gsub!(/mi/, “ma”)

match, prematch, postmatchnoneif ($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 = “-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})/;

“-06-03” =~ $rx;

($yr, $mo, $dy) = ($1, $2, $3);

rx = ‘(\d{4})-(\d{2})-(\d{2})’

m = re.search(rx, ‘-06-03’)

yr, mo, dy = m.groups()

rx = /(\d{4})-(\d{2})-(\d{2})/

m = rx.match(“-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/;

none

rx = pile(‘(\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
phpperlpythonruby
date/time typeDateTimeTime::Piece if use Time::Piece in effect, otherwise tm arraydatetime.datetimeTime
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
strftimestrftime(“%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 -08-23 19:35:59.411135-08-23 17:44:53 -0700
strptime$fmt = “Y-m-d H:i:s”;

$s = “-05-03 10:00:00”;

$t = DateTime::createFromFormat($fmt,

$s);

use Time::Local;

use Time::Piece;

$s = “-05-03 10:00:00”;

$fmt = “%Y-%m-%d %H:%M:%S”;

$t = Time::Piece->strptime($s,$fmt);

from datetime import datetime

s = ‘-05-03 10:00:00’

fmt = ‘%Y-%m-%d %H:%M:%S’

t = datetime.strptime(s, fmt)

require ‘date’

s = “-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 subtractionDateInterval object if diff method used:

$fmt = “Y-m-d H:i:s”;

$s = “-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 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 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 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?

microsecondslist($frac, $sec) = explode(” “,

microtime());

$usec = $frac * 1000 * 1000;

use Time::HiRes qw(gettimeofday);

($sec, $usec) = gettimeofday;

t.microsecondt.usec
sleepa 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)
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, 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
phpperlpythonruby
literal$a = array(1, 2, 3, 4);@a = (1, 2, 3, 4);a = [1, 2, 3, 4]a = [1, 2, 3, 4]
quote wordsnone@a = qw(do re mi);nonea = %w(do re mi)
sizecount($a)$#a + 1 or

scalar(@a)

len(a)a.size

a.length # same as size

empty 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 lengthselect 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 endarray_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)

a << 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 = (undef) x 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 argumentsparameter contains deep copyeach element passed as separate argument; use reference to pass array as single argumentparameter contains address copyparameter contains address copy
iterationforeach (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}”

end

iterate 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|

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!

membershipin_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]

maparray_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 { |

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。