perl (1987) |
python (1991) |
|
基础 |
||
模块导入 |
use strict; |
import os, 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 |
常量 |
use constant PI => 3.14; |
# uppercase identifiers |
空 |
undef |
None |
空测试 |
! defined $v |
v == None |
访问未定义变量 |
error under use strict; otherwise undef |
raises NameError |
真假 |
1 "" |
True False |
假 |
undef 0 0.0 "" "0" () |
False None 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 |
数学函数 |
use Math::Trig qw( |
from math import sqrt, exp, log, \ |
四舍五入 |
# cpan -i Number::Format |
import math |
最大最小 |
use List::Util qw(min max); |
min(1,2,3) |
除0 |
error |
raises ZeroDivisionError |
大整数 |
converted to float; use Math::BigInt to create arbitrary length integers |
becomes arbitrary length integer of type long |
大浮点数 |
inf |
raises OverflowError |
随机数 |
int(rand() * 100) |
import random |
随机数 |
srand 17; |
import random |
位操作 |
<< >> & | ^ ~ |
<< >> & | ^ ~ |
其他进制 |
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 |
sprintf |
my $fmt = "lorem %s %d %f"; |
'lorem %s %d %f' % ('ipsum', 13, 3.7) |
here document |
$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 |
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/) { |
if re.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' |
group |
$rx = qr/(\d{4})-(\d{2})-(\d{2})/; |
rx = '(\d{4})-(\d{2})-(\d{2})' |
findall |
my $s = "dolor sit amet"; |
s = 'dolor sit amet' |
匹配引用 |
"do do" =~ /(\w+) \1/ |
none |
日期时间 |
||
日期时间类型 |
Time::Piece if use Time::Piece in effect, otherwise tm array |
datetime.datetime |
当前日期时间 |
use Time::Piece; |
import datetime |
与epoch转化 |
use Time::Local; |
from datetime import datetime as dt |
当前epoch |
$epoch = time; |
import datetime |
strftime |
use Time::Piece; |
t.strftime('%Y-%m-%d %H:%M:%S') |
默认格式 |
Tue Aug 23 19:35:19 2011 |
2011-08-23 19:35:59.411135 |
字符串转为时间strptime |
use Time::Local; |
from datetime import datetime |
解析日期 |
# cpan -i Date::Parse |
# pip install python-dateutil |
时间差 |
Time::Seconds object if use Time::Piece in effect; not meaningful to subtract tm arrays |
datetime.timedelta object |
时间运算 |
use Time::Seconds; |
import datetime |
时区 |
Time::Piece has local timezone if created withlocaltime and UTC timezone if created with gmtime; tm arrays have no timezone or offset info |
a datetime object has no timezone information unless a tzinfo object is provided when it is created |
timezone name; offset from UTC; 是否夏令时 |
# cpan -i DateTime |
import time |
microseconds |
use Time::HiRes qw(gettimeofday); |
t.microsecond |
sleep |
a float argument will be truncated to an integer: |
import time |
timeout |
eval { |
import signal, time |
数组 |
||
定义 |
@a = (1, 2, 3, 4); |
a = [1, 2, 3, 4] |
quote words |
@a = qw(do re mi); |
none |
长度 |
$#a + 1 or |
len(a) |
空测试 |
!@a |
not a |
使用 |
$a[0] |
a[0] |
更新 |
$a[0] = "lorem"; |
a[0] = 'lorem' |
越界访问 |
@a = (); |
a = [] |
index |
use List::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 |
浅拷贝深拷贝 |
use Storable 'dclone' |
import copy |
数组作为函数参数 |
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" } |
for i in [1,2,3]: |
遍历 |
none; use range iteration from 0 to $#a and use index to look up value in the loop body |
a = ['do', 're', 'mi', 'fa'] |
range |
for $i (1..1_000_000) { |
range replaces xrange in Python 3: |
range数组 |
@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'] |
去重复 |
use List::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 |
map { $_ * $_ } (1,2,3) |
map(lambda x: x * x, [1,2,3]) |
filter |
grep { $_ > 1 } (1,2,3) |
filter(lambda x: x > 1, [1,2,3]) |
reduce |
use List::Util 'reduce'; |
# import needed in Python 3 only |
All/any |
# cpan -i List::MoreUtils |
all(i%2 == 0 for i in [1,2,3,4]) |
shuffle and sample |
use List::Util 'shuffle'; |
from random import shuffle, sample |
zip |
# cpan -i List::MoreUtils |
# array of 3 pairs: |
字典对象 |
||
定义 |
%d = ( t => 1, f => 0 ); |
d = { 't':1, 'f':0 } |
size |
scalar(keys %d) |
len(d) |
lookup |
$d{"t"} |
d['t'] |
out-of-bounds behavior |
%d = (); |
d = {} |
is key present |
exists $d{"y"} |
'y' in d |
delete entry |
%d = ( 1 => "t", 0 => "f" ); |
d = {1: True, 0: False} |
from array of pairs, from even length array |
@a = (1,"a",2,"b",3,"c"); |
a = [[1,'a'], [2,'b'], [3,'c']] |
merge |
%d1 = (a=>1, b=>2); |
d1 = {'a':1, 'b':2} |
invert |
%to_num = (t=>1, f=>0); |
to_num = {'t':1, 'f':0} |
iteration |
while ( ($k, $v) = each %d ) { |
for k, v in d.iteritems(): |
keys and values as arrays |
keys %d |
d.keys() |
default value, computed value |
my %counts; |
from collections import defaultdict |
函数 |
||
函数申明 |
sub add { $_[0] + $_[1] } |
def add(a, b): |
函数调用 |
add(1, 2); |
add(1, 2) |
参数丢失 |
set to undef |
raises TypeError |
参数默认值 |
sub my_log { |
import math |
变长参数 |
sub foo { |
def foo(*a): |
命名参数 |
none |
def fequal(x, y, **opts): |
pass number or string by reference |
sub foo { |
not possible |
pass array or dictionary by reference |
sub foo { |
def foo(x, y): |
return value |
return arg or last expression evaluated |
return arg or None |
multiple return values |
sub first_and_second { |
def first_and_second(a): |
lambda declaration |
$sqr = sub { $_[0] * $_[0] } |
body must be an expression: |
lambda invocation |
$sqr->(2) |
sqr(2) |
function reference |
my $func = \&add; |
func = add |
function with private state |
use feature state; |
# state not private: |
closure |
sub make_counter { |
# Python 3: |
generator |
none |
def make_counter(): |
decorator |
def logcall(f): |
|
流程控制 |
||
if |
if ( 0 == $n ) { |
if 0 == n: |
switch |
use feature 'switch'; |
none |
while |
while ( $i < 100 ) { $i++ } |
while i < 100: |
c-style for |
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) |
break, continue, redo |
last next redo |
break continue none |
control structure keywords |
do else elsif for foreach goto if unless until while |
elif else for if while |
what do does |
executes following block and returns value of last statement executed |
raises NameError unless a value was assigned to it |
statement modifiers |
print "positive\n" if $i > 0; |
none |
raise exception |
die "bad arg"; |
raise Exception('bad arg') |
catch exception |
eval { risky }; |
try: |
global variable for last exception |
$EVAL_ERROR: $@ |
last exception: sys.exc_info()[1] |
define exception |
none |
class Bam(Exception): |
catch exception by type |
none |
try: |
finally/ensure |
none |
acquire_resource() |
start thread |
use threads; |
class sleep10(threading.Thread): |
wait on thread |
$thr->join; |
thr.join() |
文件和输出 |
||
print to standard output |
print "Hello, World!\n"; |
print('Hello, World!') |
read from standard input |
$line = <STDIN>; |
line = sys.stdin.readline() |
standard file handles |
STDIN STDOUT STDERR |
sys.stdin sys.stdout sys.stderr |
open file |
open my $f, "/etc/hosts"; or |
f = open('/etc/hosts') |
open file for writing |
open my $f, ">/tmp/perl_test"; or |
f = open('/tmp/test', 'w') |
open file for append |
with open('/tmp/test') as f: |
|
close file |
close $f; or |
f.close() |
read line |
$line = <$f>; or |
f.readline() |
iterate over file by line |
while ($line = <$f>) { |
for line in f: |
chomp |
chomp $line; |
line = line.rstrip('\r\n') |
read entire file into array or string |
@a = <$f>; |
a = f.readlines() |
write to file |
print $f "lorem ipsum"; |
f.write('lorem ipsum') |
flush file handle |
use IO::Handle; |
f.flush() |
file test, regular file test |
If (-e "/etc/hosts") {print exist;} |
os.path.exists('/etc/hosts') |
copy file, remove file, rename file |
use File::Copy; |
import shutil |
set file permissions |
chmod 0755, "/tmp/foo"; |
os.chmod('/tmp/foo', 0755) |
temporary file |
use File::Temp; |
import tempfile |
in memory file |
my ($f, $s); |
from StringIO import StringIO |
目录操作 |
||
build pathname |
use File::Spec; |
os.path.join('/etc', 'hosts') |
dirname and basename |
use File::Basename; |
os.path.dirname('/etc/hosts') |
absolute pathname |
use Cwd; |
os.path.abspath('..') |
iterate over directory by file |
use File::Basename; |
for filename in os.listdir('/etc'): |
make directory |
use File::Path 'make_path'; |
dirname = '/tmp/foo/bar' |
recursive copy |
# cpan -i File::Copy::Recursive |
import shutil |
remove empty directory |
rmdir "/tmp/foodir"; |
os.rmdir('/tmp/foodir') |
remove directory and contents |
use File::Path 'remove_tree'; |
import shutil |
directory test |
-d "/tmp" |
os.path.isdir('/tmp') |
命令行操作 |
||
command line args, script name |
scalar(@ARGV) |
len(sys.argv)-1 |
getopt |
use Getopt::Long; |
import argparse |
get and set environment variable |
$ENV{"HOME"} |
os.getenv('HOME') |
exit |
exit 0; |
sys.exit(0) |
set signal handller |
$SIG{INT} = sub { |
import signal |
executable test |
-x "/bin/ls" |
os.access('/bin/ls', os.X_OK) |
external command |
system("ls -l /tmp") == 0 or |
if os.system('ls -l /tmp'): |
escaped external command |
$path = <>; |
import subprocess |
backticks |
my $files = `ls -l /tmp`; or |
import subprocess |
__________________________________________ |