perl (1987) |
python (1991) |
|
基础 |
||
usestrict; |
importos, re, sys |
|
$ perl -v |
$ python -V |
|
执行脚本 |
$ perl foo.pl |
$ python foo.py |
交互模式 |
$ perl -de 0 |
$ python |
执行语句 |
$ perl -e 'print("hi\n")' |
$ python -c "print('hi')" |
; |
\n (newline) |
|
语句块 |
{} |
Indent |
注释 |
# comment |
# comment |
多行注释 |
=for |
use triple quote string literal: |
变量和操作符 |
||
$v = 1; |
v= 1 |
|
赋值 |
($x, $y, $z) = (1, 2, 3); |
x,y,z = 1, 2, 3 |
($x, $y) = ($y, $x); |
x,y = y, x |
|
+= -= *=none/= %= **= |
# do not return values: |
|
my$x = 1; |
none |
|
my$v; |
# in function body: |
|
our($g1,$g2) = (7, 8); |
g1,g2 = 7, 8 |
|
useconstantPI => 3.14; |
# uppercase identifiers |
|
undef |
None |
|
! defined $v |
v ==None |
|
error underuse strict; otherwise undef |
raisesNameError |
|
1 "" |
True False |
|
undef0 0.0 "" "0"() |
FalseNone 0 0.0 ''[] {} |
|
&& || ! |
and or not |
|
$x > 0 ? $x : -$x |
x if x > 0 else-x |
|
numbers only:== != > < >= <= |
comparison operators are chainable: |
|
数学运算 |
||
7 + "12" |
7 + int('12') |
|
+ - * /none% ** |
+ - * / // % ** |
|
取余 |
int( 13 / 5 ) |
13 // 5 |
13 / 5 |
float(13) / 5 |
|
useMath::Trigqw( |
frommath importsqrt, exp, log, \ |
|
# cpan -i Number::Format |
importmath |
|
useList::Utilqw(min max); |
min(1,2,3) |
|
除0 |
error |
raisesZeroDivisionError |
converted to float; useMath::BigInt to create arbitrary length integers |
becomes arbitrary length integer of typelong |
|
inf |
raisesOverflowError |
|
int(rand() * 100) |
importrandom |
|
srand17; |
importrandom |
|
位操作 |
<< >> & | ^ ~ |
<< >> & | ^ ~ |
0b101010 |
0b101010 |
|
"don't say \"no\"" |
'don\'t say "no"' |
|
yes |
triple quote literals only |
|
double quoted: |
single and double quoted: |
|
my$count = 3; |
count= 3 |
|
my $fmt = "lorem %s %d %f"; |
'lorem %s %d %f'% ('ipsum', 13, 3.7) |
|
$word ="amet"; |
‘’’ |
|
my$s = "Hello, "; |
s= 'Hello, ' |
|
my$hbar = "-"x 80; |
hbar= '-'* 80 |
|
split(/\s+/,"do re mi fa") |
'do re mi fa'.split() |
|
join(" ",qw(do re mi fa)) |
' '.join(['do','re','mi','fa']) |
|
uc("lorem") |
'lorem'.upper() |
|
字符串strip |
# cpan -i Text::Trim |
' lorem '.strip() |
sprintf("%-10s","lorem") |
'lorem'.ljust(10) |
|
length("lorem") |
len('lorem') |
|
index("lorem ipsum","ipsum") |
'do re re'.index('re') |
|
substr("lorem ipsum", 6, 5) |
'lorem ipsum'[6:11] |
|
can't use index notation with strings: |
'lorem ipsum'[6] |
|
chr(65) |
chr(65) |
|
/lorem|ipsum/ |
re.compile('lorem|ipsum') |
|
char class abbrevs: |
char class abbrevs: |
|
if($s =~ /1999/) { |
ifre.search('1999', s): |
|
"Lorem"=~ /lorem/i |
re.search('lorem','Lorem', re.I) |
|
i m s p x |
re.I re.M re.S re.X |
|
my$s= "do re mi mi mi"; |
s= 'do re mi mi mi' |
|
$rx =qr/(\d{4})-(\d{2})-(\d{2})/; |
rx= '(\d{4})-(\d{2})-(\d{2})' |
|
my$s= "dolor sit amet"; |
s= 'dolor sit amet' |
|
"do do"=~ /(\w+) \1/ |
none |
|
Time::Pieceif use Time::Piece in effect, otherwise tm array |
datetime.datetime |
|
useTime::Piece; |
importdatetime |
|
与epoch转化 |
useTime::Local; |
fromdatetime importdatetime asdt |
当前epoch |
$epoch =time; |
importdatetime |
useTime::Piece; |
t.strftime('%Y-%m-%d %H:%M:%S') |
|
Tue Aug 23 19:35:19 2011 |
2011-08-23 19:35:59.411135 |
|
字符串转为时间strptime |
useTime::Local; |
fromdatetime importdatetime |
# cpan -i Date::Parse |
# pip install python-dateutil |
|
Time::Secondsobject if use Time::Piece in effect; not meaningful to subtract tm arrays |
datetime.timedeltaobject |
|
useTime::Seconds; |
importdatetime |
|
Time::Piecehas local timezone if created withlocaltime and UTC timezone if created with gmtime;tm arrays have no timezone or offset info |
adatetime object has no timezone information unless a tzinfoobject is provided when it is created |
|
# cpan -i DateTime |
importtime |
|
useTime::HiResqw(gettimeofday); |
t.microsecond |
|
a float argument will be truncated to an integer: |
importtime |
|
eval{ |
importsignal, time |
|
@a= (1, 2, 3, 4); |
a= [1, 2, 3, 4] |
|
@a= qw(do re mi); |
none |
|
$#a+ 1 or |
len(a) |
|
!@a |
nota |
|
$a[0] |
a[0] |
|
$a[0] ="lorem"; |
a[0] ='lorem' |
|
@a= (); |
a= [] |
|
useList::Util'first'; |
a= ['x','y','z','w'] |
|
select 3rd and 4th elements: |
select 3rd and 4th elements: |
|
@a[1..$#a] |
a[1:] |
|
@a= (6,7,8); |
a= [6,7,8] |
|
@a= (6,7,8); |
a= [6,7,8] |
|
@a= (1,2,3); |
a= [1,2,3] |
|
@a= (undef)x 10; |
a = [None] * 10 |
|
useStorable'dclone' |
importcopy |
|
each element passed as separate argument; use reference to pass array as single argument |
parameter contains address copy |
|
for$i (1, 2, 3) { print"$i\n" } |
fori in[1,2,3]: |
|
none; use range iteration from0 to $#a and use index to look up value in the loop body |
a= ['do','re','mi','fa'] |
|
for$i (1..1_000_000) { |
rangereplaces xrange in Python 3: |
|
@a= 1..10; |
a= range(1, 11) |
|
@a= (1,2,3); |
a= [1,2,3] |
|
@a= qw(b A a B); |
a= ['b','A','a','B'] |
|
useList::MoreUtils'uniq'; |
a= [1,2,2,3] |
|
7 ~~@a |
7 in a |
|
{1,2} & {2,3,4} |
||
{1,2} | {2,3,4} |
||
{1,2,3} - {2} |
||
map{ $_ * $_ } (1,2,3) |
map(lambdax: x * x, [1,2,3]) |
|
grep{ $_ > 1 } (1,2,3) |
filter(lambdax: x > 1, [1,2,3]) |
|
useList::Util'reduce'; |
# import needed in Python 3 only |
|
# cpan -i List::MoreUtils |
all(i%2 == 0fori in[1,2,3,4]) |
|
useList::Util'shuffle'; |
fromrandom importshuffle, sample |
|
# cpan -i List::MoreUtils |
# array of 3 pairs: |
|
%d= ( t=> 1, f=> 0 ); |
d= { 't':1,'f':0 } |
|
scalar(keys%d) |
len(d) |
|
$d{"t"} |
d['t'] |
|
%d= (); |
d= {} |
|
exists$d{"y"} |
'y'in d |
|
%d= ( 1 => "t", 0 =>"f"); |
d= {1: True, 0:False} |
|
@a= (1,"a",2,"b",3,"c"); |
a= [[1,'a'], [2,'b'], [3,'c']] |
|
%d1= (a=>1,b=>2); |
d1= {'a':1,'b':2} |
|
%to_num= (t=>1,f=>0); |
to_num= {'t':1,'f':0} |
|
while( ($k, $v) = each%d ) { |
fork, v ind.iteritems(): |
|
keys%d |
d.keys() |
|
my%counts; |
fromcollections importdefaultdict |
|
subadd { $_[0] +$_[1] } |
defadd(a, b): |
|
add(1, 2); |
add(1, 2) |
|
set toundef |
raisesTypeError |
|
submy_log{ |
importmath |
|
subfoo { |
deffoo(*a): |
|
none |
deffequal(x, y, **opts): |
|
subfoo { |
not possible |
|
subfoo { |
deffoo(x, y): |
|
returnarg or last expression evaluated |
returnarg or None |
|
subfirst_and_second{ |
deffirst_and_second(a): |
|
$sqr =sub{ $_[0] *$_[0] } |
body must be an expression: |
|
$sqr->(2) |
sqr(2) |
|
my$func = \&add; |
func= add |
|
usefeaturestate; |
# state not private: |
|
submake_counter{ |
# Python 3: |
|
none |
defmake_counter(): |
|
def logcall(f): |
||
if( 0 == $n ) { |
if0 == n: |
|
usefeature'switch'; |
none |
|
while( $i < 100 ) { $i++ } |
whilei < 100: |
|
for( $i=0; $i <= 10; $i++ ) { |
none |
|
Foreach |
@a = (1..5); foreach (@a) { print "$_\n"; } @a = (1..5); for (@a) { print "$_\n" } |
a = ['do', 're', 'mi', 'fa'] for i, s in enumerate(a): print('%s at index %d' % (s, i)) for i in [1,2,3]: print(i) |
last next redo |
break continuenone |
|
do else elsif for foreach goto if unless until while |
elif else for if while |
|
executes following block and returns value of last statement executed |
raisesNameError unless a value was assigned to it |
|
print"positive\n"if $i > 0; |
none |
|
die"bad arg"; |
raiseException('bad arg') |
|
eval{ risky }; |
try: |
|
$EVAL_ERROR: $@ |
last exception:sys.exc_info()[1] |
|
none |
classBam(Exception): |
|
none |
try: |
|
none |
acquire_resource() |
|
usethreads; |
classsleep10(threading.Thread): |
|
$thr->join; |
thr.join() |
|
print"Hello, World!\n"; |
print('Hello, World!') |
|
$line = <STDIN>; |
line= sys.stdin.readline() |
|
STDIN STDOUT STDERR |
sys.stdin sys.stdout sys.stderr |
|
openmy $f, "/etc/hosts";or |
f= open('/etc/hosts') |
|
openmy $f, ">/tmp/perl_test";or |
f= open('/tmp/test','w') |
|
with open('/tmp/test')asf: |
||
close$f; or |
f.close() |
|
$line = <$f>;or |
f.readline() |
|
while($line = <$f>) { |
forline inf: |
|
chomp$line; |
line= line.rstrip('\r\n') |
|
@a= <$f>; |
a= f.readlines() |
|
print$f "lorem ipsum"; |
f.write('lorem ipsum') |
|
useIO::Handle; |
f.flush() |
|
If (-e"/etc/hosts") {print exist;} |
os.path.exists('/etc/hosts') |
|
useFile::Copy; |
importshutil |
|
chmod0755, "/tmp/foo"; |
os.chmod('/tmp/foo', 0755) |
|
useFile::Temp; |
importtempfile |
|
my($f,$s); |
fromStringIO importStringIO |
|
useFile::Spec; |
os.path.join('/etc','hosts') |
|
useFile::Basename; |
os.path.dirname('/etc/hosts') |
|
useCwd; |
os.path.abspath('..') |
|
useFile::Basename; |
forfilename inos.listdir('/etc'): |
|
useFile::Path'make_path'; |
dirname= '/tmp/foo/bar' |
|
# cpan -i File::Copy::Recursive |
importshutil |
|
rmdir"/tmp/foodir"; |
os.rmdir('/tmp/foodir') |
|
useFile::Path'remove_tree'; |
importshutil |
|
-d"/tmp" |
os.path.isdir('/tmp') |
|
scalar(@ARGV) |
len(sys.argv)-1 |
|
useGetopt::Long; |
importargparse |
|
$ENV{"HOME"} |
os.getenv('HOME') |
|
exit0; |
sys.exit(0) |
|
$SIG{INT} =sub{ |
importsignal |
|
-x"/bin/ls" |
os.access('/bin/ls', os.X_OK) |
|
system("ls -l /tmp") == 0 or |
ifos.system('ls -l /tmp'): |
|
$path = <>; |
importsubprocess |
|
my$files = `ls -l /tmp`;or |
importsubprocess |
|
__________________________________________ |