作者:iTech
出处:http://itech.cnblogs.com/
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( sqrt exp log sin cos tan asin acos atan atan2 | from math import sqrt, exp, log, \ |
四舍五入 | # cpan -i Number::Format int($x) | import math int(x) |
最大最小 | use List::Util qw(min max); min(1,2,3); | 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 random.randint(0,99) |
随机数 | srand 17; my $sd = srand; | import random random.seed(17) |
位操作 | << >> & | ^ ~ | << >> & | ^ ~ |
其他进制 | 0b101010 | 0b101010 |
字符串操作 | ||
字符串 | "don't say \"no\"" | 'don\'t say "no"' |
多行字符串 | yes | triple quote literals only |
转义 | double quoted: single quoted: | single and double quoted: Python 3: |
变量替换 | my $count = 3; | count = 3 |
sprintf | my $fmt = "lorem %s %d %f"; | 'lorem %s %d %f' % ('ipsum', 13, 3.7) fmt = 'lorem {0} {1} {2}' |
here document | $word = "amet"; | ‘’’ |
字符串连接 | my $s = "Hello, "; | s = 'Hello, ' juxtaposition can be used to concatenate literals: |
字符串复制 | 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 trim " lorem " | ' 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: anchors: ^ $ \A \b \B \z \Z | char class abbrevs: anchors: ^ $ \A \b \B \Z |
正则表达式匹配 | 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/ my $s = "do re"; | none rx = re.compile('(\w+) (\w+)') |
日期时间 | ||
日期时间类型 | Time::Piece if use Time::Piece in effect, otherwise tm array | datetime.datetime |
当前日期时间 | use Time::Piece; my $t = localtime(time); | import datetime t = datetime.datetime.now() |
与epoch转化 | use Time::Local; my $epoch = timelocal($t); | from datetime import datetime as dt epoch = int(t.strftime("%s")) |
当前epoch | $epoch = time; | import datetime t = datetime.datetime.now() |
strftime | use Time::Piece; $t = localtime(time); | 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; $s = "2011-05-03 10:00:00"; | from datetime import datetime s = '2011-05-03 10:00:00' |
解析日期 | # cpan -i Date::Parse $epoch = str2time("July 7, 1999"); | # pip install python-dateutil s = 'July 7, 1999' |
时间差 | Time::Seconds object if use Time::Piece in effect; not meaningful to subtract tm arrays | datetime.timedelta object |
时间运算 | use Time::Seconds; $now = localtime(time); | import datetime delta = datetime.timedelta( |
时区 | 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 $dt = DateTime->now(); $tz->name; | import time tm = time.localtime() |
microseconds | use Time::HiRes qw(gettimeofday); ($sec, $usec) = gettimeofday; | t.microsecond |
sleep | a float argument will be truncated to an integer: | import time time.sleep(0.5) |
timeout | eval { | import signal, time class Timeout(Exception): pass def timeout_handler(signo, fm): signal.signal(signal.SIGALRM, try: |
数组 | ||
定义 | @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 = qw(x y z w); | 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' my @a = (1,2,[3,4]); | import copy a = [1,2,[3,4]] |
数组作为函数参数 | 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: |
@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'; my @a = (1,2,2,3); | 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(lambda x: x * x, [1,2,3]) | |
grep { $_ > 1 } (1,2,3) | filter(lambda x: x > 1, [1,2,3]) | |
use List::Util 'reduce'; reduce { $x + $y } 0, (1,2,3) | # import needed in Python 3 only reduce(lambda x, y: x+y, [1,2,3], 0) | |
All/any | # cpan -i List::MoreUtils all { $_ % 2 == 0 } (1,2,3,4) | all(i%2 == 0 for i in [1,2,3,4]) |
use List::Util 'shuffle'; @a = (1, 2, 3, 4); | from random import shuffle, sample a = [1, 2, 3, 4] | |
# cpan -i List::MoreUtils @nums = (1, 2, 3); | # 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']] 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 ) { | for k, v in d.iteritems(): Python 3: | |
keys %d | d.keys() Python 3: | |
my %counts; define a tied hash for computed values and defaults other than zero or empty string | from collections import defaultdict counts = defaultdict(lambda: 0) class Factorial(dict): factorial = Factorial() | |
函数 | ||
sub add { $_[0] + $_[1] } sub add { | def add(a, b): | |
add(1, 2); parens are optional: | add(1, 2) | |
set to undef | raises TypeError | |
sub my_log { log($x)/log($base); my_log(42); | import math def my_log(x, base=10): my_log(42) | |
变长参数 | sub foo { | def foo(*a): |
命名参数 | none | def fequal(x, y, **opts): fequal(1.0, 1.001) |
sub foo { my $n = 7; | not possible | |
sub foo { my @a = (1,2,3); | def foo(x, y): a = [1,2,3] | |
return arg or last expression evaluated | return arg or None | |
sub first_and_second { | def first_and_second(a): x, y = first_and_second([1,2,3]) | |
$sqr = sub { $_[0] * $_[0] } | body must be an expression: | |
$sqr->(2) | sqr(2) | |
my $func = \&add; | func = add | |
use feature state; sub counter { print counter() . "\n"; | # state not private: counter.i = 0 | |
sub make_counter { | # Python 3: nays = make_counter() | |
none | def make_counter(): nays = make_counter() | |
def logcall(f): @logcall square(5) | ||
流程控制 | ||
if ( 0 == $n ) { | if 0 == n: | |
use feature 'switch'; given ($n) { | none | |
while ( $i < 100 ) { $i++ } | while i < 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 continue none | |
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 | raises NameError unless a value was assigned to it | |
print "positive\n" if $i > 0; | none | |
die "bad arg"; | raise Exception('bad arg') | |
eval { risky }; | try: | |
$EVAL_ERROR: $@ | last exception: sys.exc_info()[1] | |
none | class Bam(Exception): | |
none | try: | |
none | acquire_resource() | |
use threads; $func = sub { sleep 10 }; | class sleep10(threading.Thread): thr = sleep10() | |
$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 | |
open my $f, "/etc/hosts"; or | f = open('/etc/hosts') | |
open my $f, ">/tmp/perl_test"; or | f = open('/tmp/test', 'w') | |
with open('/tmp/test') as f: | ||
close $f; or | f.close() | |
$line = <$f>; or | f.readline() | |
while ($line = <$f>) { | for line in f: | |
chomp $line; | line = line.rstrip('\r\n') | |
@a = <$f>; | a = f.readlines() | |
print $f "lorem ipsum"; | f.write('lorem ipsum') | |
use IO::Handle; $f->flush(); | f.flush() | |
If (-e "/etc/hosts") {print exist;} | os.path.exists('/etc/hosts') | |
use File::Copy; copy("/tmp/foo", "/tmp/bar"); | import shutil shutil.copy('/tmp/foo', '/tmp/bar') | |
chmod 0755, "/tmp/foo"; | os.chmod('/tmp/foo', 0755) | |
use File::Temp; $f = File::Temp->new(); print "tmp file: "; | import tempfile f = tempfile.NamedTemporaryFile( print("tmp file: %s" % f.name) | |
my ($f, $s); | from StringIO import StringIO f = StringIO() Python 3 moved StringIO to the io module | |
目录操作 | ||
use File::Spec; File::Spec->catfile("/etc", "hosts") | os.path.join('/etc', 'hosts') | |
use File::Basename; print dirname("/etc/hosts"); | os.path.dirname('/etc/hosts') | |
use Cwd; Cwd::abs_path("..") | os.path.abspath('..') | |
use File::Basename; while ( </etc/*> ) { | for filename in os.listdir('/etc'): | |
use File::Path 'make_path'; make_path "/tmp/foo/bar"; | dirname = '/tmp/foo/bar' | |
# cpan -i File::Copy::Recursive dircopy "/tmp/foodir", | import shutil shutil.copytree('/tmp/foodir', | |
rmdir "/tmp/foodir"; | os.rmdir('/tmp/foodir') | |
use File::Path 'remove_tree'; remove_tree "/tmp/foodir"; | import shutil shutil.rmtree('/tmp/foodir') | |
-d "/tmp" | os.path.isdir('/tmp') | |
命令行操作 | ||
command line args, script name | scalar(@ARGV) | len(sys.argv)-1 |
getopt | use Getopt::Long; my ($src, $help); sub usage { GetOptions("file=s" => \$src, usage if $help; | import argparse parser = argparse.ArgumentParser() args = parser.parse_args() |
get and set environment variable | $ENV{"HOME"} $ENV{"PATH") = "/bin"; | os.getenv('HOME') os.environ['PATH'] = '/bin' |
exit | exit 0; | sys.exit(0) |
set signal handller | $SIG{INT} = sub { | import signal def handler(signo, frame): |
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 cmd = ['ls', '-l', '/tmp'] |
backticks | my $files = `ls -l /tmp`; or | import subprocess cmd = ['ls', '-l', '/tmp'] |
|
完!