|
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) or ;
|
语句块
|
{}
|
Indent
|
注释
|
# comment
|
# comment
|
多行注释
|
=for comment line another line =cut
|
use triple quote string literal: '''comment line another line'''
|
变量和操作符
|
赋值
|
$v = 1;
|
v = 1
|
赋值
|
($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) = ($y, $x);
|
x, y = y, x
|
操作符
|
+= -= *= none /= %= **= .= x= &&= ||= ^= <<= >>= &= |= ^=
|
# do not return values: += -= *= /= //= %= **= += *= &= |= ^= <<= >>= &= |= ^=
|
自增
|
my $x = 1; my $y = ++$x; my $z = --$y;
|
none
|
局部变量
|
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
|
全局变量
|
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
|
常量
|
use constant PI => 3.14;
|
# uppercase identifiers # constant by convention PI = 3.14
|
空
|
undef
|
None
|
空测试
|
! defined $v
|
v == None v is None
|
访问未定义变量
|
error under use strict; otherwise undef
|
raises NameError
|
真假
|
1 ""
|
True False
|
假
|
undef 0 0.0 "" "0" ()
|
False None 0 0.0 '' [] {}
|
逻辑运算
|
&& || ! lower precedence: and or xor not
|
and or not
|
条件
|
$x > 0 ? $x : -$x
|
x if x > 0 else -x
|
比较
|
numbers only: == != > < >= <= strings: eq ne gt lt ge le
|
comparison operators are chainable: == != > < >= <=
|
数学运算
|
类型转化
|
7 + "12" 73.9 + ".037" "value: " . 8
|
7 + int('12') 73.9 + float('.037') 'value: ' + str(8)
|
算术运算
|
+ - * / none % **
|
+ - * / // % **
|
取余
|
int ( 13 / 5 ) none
|
13 // 5 q, r = divmod(13, 5)
|
浮点除法
|
13 / 5
|
float(13) / 5 # Python 3: 13 / 5
|
数学函数
|
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
|
四舍五入
|
# 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)
|
最大最小
|
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])
|
除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) rand() none
|
import random
random.randint(0,99) random.random() random.gauss(0,1)
|
随机数
|
srand 17;
my $sd = srand; srand($sd);
|
import random
random.seed(17) sd = random.getstate() random.setstate(sd)
|
位操作
|
<< >> & | ^ ~
|
<< >> & | ^ ~
|
其他进制
|
0b101010 052 0x2a
|
0b101010 052 0x2a
|
字符串操作
|
字符串
|
"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\""""
|
多行字符串
|
yes
|
triple quote literals only
|
转义
|
double quoted: \a \b \cx \e \f \n \r \t \xhh \x{hhhh} \ooo Perl 5.14: \o{ooo}
single quoted: \' \\
|
single and double quoted: \newline \\ \' \" \a \b \f \n \r \t \v \ooo \xhh
Python 3: \uhhhh \Uhhhhhhhh
|
变量替换
|
my $count = 3; my $item = "ball"; print "$count ${item}s\n";
|
count = 3 item = 'ball' print(‘%s %s’ % (count, item))
|
sprintf
|
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)
|
here document
|
$word = "amet"; $s = <<EOF; lorem ipsum dolor sit $word EOF
|
‘’’ ‘’’
|
字符串连接
|
my $s = "Hello, "; my $s2 = $s . "World!";
|
s = 'Hello, ' s2 = s + 'World!'
juxtaposition can be used to concatenate literals: s2 = 'Hello, ' "World!"
|
字符串复制
|
my $hbar = "-" x 80;
|
hbar = '-' * 80
|
字符串分隔
|
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')
|
字符串连接
|
join(" ", qw(do re mi fa))
|
' '.join(['do', 're', 'mi', 'fa'])
|
字符串大小写
|
uc("lorem") lc("LOREM") ucfirst("lorem")
|
'lorem'.upper() 'LOREM'.lower() 'lorem'.capitalize()
|
字符串strip
|
# cpan -i Text::Trim
|
请发表评论