比较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 ...
随机推荐
- Python学习笔记_week1
一.编程语言的分类 编译型和解释型.静态语言和动态语言.强类型定义语言和弱类型定义语言,Python是一门动态解释型的强类型定义语言. Python的优缺点 Python解释器:CPython.IPy ...
- c#调用带输出参数的存储过程
sql server中编写一个存储过程: CREATE PROCEDURE ProGetPWD @username varchar(20), @password varchar(20) OUTPUT ...
- 选择、操作web元素
11月1日 什么是web元素 Selenium自动化主要就是:选择界面元素,操作界面元素(输入操作:点击.输入文字.拖拽等,输出操作:获取元素的各种属性),根据界面上获取的数据进行分析和处理 选择元素 ...
- 完美解决ubuntu下sublime中文输入问题
声明 1.本人整理文章,转载请注明出处. 2.参考资料 http://my.oschina.net/tsl0922/blog/113495 问题描述 在ubuntu下想使用sublime,但是不能输入 ...
- JDK7和JDK8concurrentHashmap区别
哈希表 1.介绍 哈希表就是一种以 键-值(key-indexed) 存储数据的结构,我们只要输入待查找的值即key,即可查找到其对应的值. 哈希的思路很简单,如果所有的键都是整数,那么就可以使用一个 ...
- electron安装到第一个实例
1.node.js下载,然后安装.下载地址:链接:http://pan.baidu.com/s/1o7TONhS 密码:fosa 2.cmd下输入:npm install electron-prebu ...
- 500G JAVA视频网盘分享 (JEECG开源社区)
500 G JAVA视频网盘分享(JEECG开源社区) [涵盖从java入门到深入架构,Linux.云计算.分布式.大数据Hadoop.ios.Android.互联网技术应有尽有] J ...
- vue.js 初级之一
vue.js 是一个构建数据驱动的 web 界面 渐进式驱动框架. 引用的话,直接使用script标签引入就可以了: <script src="./lib/vue.js"&g ...
- C语言复习:内存模型1
数据类型本质分析 数据类型概念 "类型"是对数据的抽象; 类型相同的数据有相同的表现形式/存储格式以及相关的操作; 程序中使用的所有数据都必定属于某一种数据类型; 数据类型本质思考 ...
- tar 打包当前目录下文件但不包括该录
今天想打包一些文件,但是不想把该目录打包进去 比如我想把test目录下文件打个包,安装正常的命令来 tar zcf test.tar.gz test 这样肯定会把test目录也打进去,解压后肯定是te ...