比较perl+python
http://hyperpolyglot.org/scripting
比较perl+python
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: == != > < >=< >=& | ^ ~
> & | ^ ~
其他进制
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 =
页:
[1]