比较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( 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'] |
|
完!
比较perl+python的更多相关文章
- awk,perl,python的命令行参数处理
Python,Perl,Bash命令行参数 Part I 日常经常性的和Perl,Python,Bash打交道,但是又经常性的搞混他们之间,在命令行上的特殊性和index的区别,Python真的是人性 ...
- split function of Perl,Python,Awk
使用中常用到Perl,Python,AWK,R, 虽然Java,C,C++,Vala也学过但是就是不喜欢,你说怎么办. 看来一辈子脚本的命. Perl @rray = split /PATTERN/, ...
- 正则表达式-使用说明Regular Expression How To (Perl, Python, etc)
notepad++ wiki about regular expression 正则表达式-使用说明Regular Expression How To (Perl, Python, etc) http ...
- shell,perl,python的区别
shell+sed+awk严格的讲, shell不是一种编程语言, 但是shell有自己的控制流结构(判断,循环,选择),运算以及函数等编程语言特性, 加上shell命令组织在一起构成脚本, 能够完成 ...
- RHEL / CentOS Linux Install Core Development Tools Automake, Gcc (C/C++), Perl, Python & Debuggers
how do I install all developer tools such as GNU GCC C/C++ compilers, make and others, after install ...
- Perl & Python编写CGI
近期偶然玩了一下CGI,收集点资料写篇在这里留档. 如今想做HTTP Cache回归測试了,为了模拟不同的响应头及数据大小.就须要一个CGI按须要传回指定的响应头和内容.这是从老外的測试页面学习到的经 ...
- Makefile中怎样调用python和perl文件为自己提供须要的数据
Makefile中怎样调用python和perl文件为自己提供须要的数据,利用print函数对外输出数据 实例代码例如以下 perl.pl #!/usr/bin/perl print("he ...
- Python与Perl的相似与差别
Python version 3.7版本 00.命令行交互 命令行交互 Perl Python perl -e <Perl代码> #Unix/Linux/Windows/DOS 直 ...
- Json概述以及python对json的相关操作
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析和生成.它基于JavaScript Programming Langu ...
随机推荐
- 增删改查列表angular.js页面实现
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...
- 2. instr用法
跟oracle中的instr用法一样: SQL> select count(*) from t where instr(title,‟oracle‟)>0; COUNT(*) ———- 5 ...
- nslookup和dig命令
nslookup与dig两个工具功能类似,都可以查询制定域名所对应的ip地址,所不同的是dig工具可以从该域名的官方dns服务器上查询到精确的权威解答,而nslookup只会得到DNS解析服务器保存在 ...
- django之relacted.py(探秘django的关联field)
生成model类对象时,传入的每个field对象都会调用其contribute_to_class函数,生成对应的属性. def contribute_to_class(self, cls, name, ...
- idea 未实现接口红线提示,重复代码波浪线提示,自动换行,控制台输出内容自动换行
01,Could not autowire. No beans of 'UserMapper' type found 01.1,问题描述,通过反射动态实现的接口在调用时会出现以上提示,常见的如 ORM ...
- div的全屏与退出全屏
div的全屏与退出全屏 作用:将div全屏与退出全屏,一般播放器使用较多. html按钮: <button onclick="showFull();"> 全屏 < ...
- Mysql 索引 n-gram分词引擎使用
概述: 类似于书籍的目录,找到一本书的特定内容,需要首先找到内容对应页码,定位对应页码 存储引擎使用类似方法进行数据查找,先找到索引中对应值,然后根据匹配的索引找到对应行 实现原理: 索引的实现通常使 ...
- php计算程序运行时间
这里介绍一下 microtime() 这个函数,microtime() 用的不多,但是不能不知道这个函数,它是返回当前 Unix 时间戳和微秒数.例如:echo microtime(); 会返回:0. ...
- AS2在FLASH中调用EXE文件方法详细说明 已测试可行
熟悉FLASH功能的朋友都知道fscommand在FLASH中是一个经常用来控制窗口全屏或退出的命令,同时它也是FLASH调用外部可执行程序的一种方法,使用fscommand命令格式如下: fscom ...
- Cmake 编译opengl开源库glfw工程及使用
使用的是cmake gui进行编译的,路径输入好之后,点configure配置vs版本,这里是vs2013版本,然后如果画面出现红色的 需要再点击一下 Generate 然后直接点open proje ...