比较perl+python
作者: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( |
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) |
$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() |
|
# 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/) { |
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' |
|
$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::Piece if use Time::Piece in effect, otherwise tm array |
datetime.datetime |
|
use Time::Piece; |
import datetime |
|
use Time::Local; |
from datetime import datetime as dt |
|
$epoch = time; |
import datetime |
|
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 |
|
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 |
|
# cpan -i DateTime |
import time |
|
use Time::HiRes qw(gettimeofday); |
t.microsecond |
|
a float argument will be truncated to an integer: |
import time |
|
eval { |
import signal, time |
|
@a = (1, 2, 3, 4); |
a = [1, 2, 3, 4] |
|
@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 = [] |
|
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'] |
|
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'; |
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'; |
# import needed in Python 3 only |
|
# cpan -i List::MoreUtils |
all(i%2 == 0 for i in [1,2,3,4]) |
|
use List::Util 'shuffle'; |
from random import shuffle, 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 ) { |
for k, v in d.iteritems(): |
|
keys %d |
d.keys() |
|
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): |
|
sub foo { |
not possible |
|
sub foo { |
def foo(x, y): |
|
return arg or last expression evaluated |
return arg or None |
|
sub first_and_second { |
def first_and_second(a): |
|
$sqr = sub { $_[0] * $_[0] } |
body must be an expression: |
|
$sqr->(2) |
sqr(2) |
|
my $func = \&add; |
func = add |
|
use feature state; |
# state not private: |
|
sub make_counter { |
# Python 3: |
|
none |
def make_counter(): |
|
def logcall(f): |
||
if ( 0 == $n ) { |
if 0 == n: |
|
use feature 'switch'; |
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; |
class sleep10(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 |
|
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() |
|
If (-e "/etc/hosts") {print exist;} |
os.path.exists('/etc/hosts') |
|
use File::Copy; |
import shutil |
|
chmod 0755, "/tmp/foo"; |
os.chmod('/tmp/foo', 0755) |
|
use File::Temp; |
import tempfile |
|
my ($f, $s); |
from StringIO import StringIO |
|
use File::Spec; |
os.path.join('/etc', 'hosts') |
|
use File::Basename; |
os.path.dirname('/etc/hosts') |
|
use Cwd; |
os.path.abspath('..') |
|
use File::Basename; |
for filename in os.listdir('/etc'): |
|
use File::Path 'make_path'; |
dirname = '/tmp/foo/bar' |
|
# cpan -i File::Copy::Recursive |
import shutil |
|
rmdir "/tmp/foodir"; |
os.rmdir('/tmp/foodir') |
|
use File::Path 'remove_tree'; |
import shutil |
|
-d "/tmp" |
os.path.isdir('/tmp') |
|
scalar(@ARGV) |
len(sys.argv)-1 |
|
use Getopt::Long; |
import argparse |
|
$ENV{"HOME"} |
os.getenv('HOME') |
|
exit 0; |
sys.exit(0) |
|
$SIG{INT} = sub { |
import signal |
|
-x "/bin/ls" |
os.access('/bin/ls', os.X_OK) |
|
system("ls -l /tmp") == 0 or |
if os.system('ls -l /tmp'): |
|
$path = <>; |
import subprocess |
|
my $files = `ls -l /tmp`; or |
import subprocess |
|
|
完!
posted on 2015-07-23 12:22 Paulcnblogs 阅读(407) 评论(0) 编辑 收藏 举报