Python語法簡單,而且通過縮進的方式來表現層次結構,代碼非常簡明易懂,對初學者來說,比較容易上手。
Perl的模式匹配非常強大,同時匹配的符號有很多種,難以閱讀和維護。
在文本處理方面,python通過加載re模塊來實現模式匹配的查找和替換。而Perl內置就有模式匹配功能。
note:內置命令和外部命令的區別。
通過代碼來直接做比較。
python版:
#!/usr/bin/python
import re
import fileinput
exists_re = re.compile(r'^(.*?) INFO.*Such a record already exists', re.I)
location_re = re.compile(r'^AwbLocation (.*?) insert into', re.I)
for line in fileinput.input():
fn = fileinput.filename()
currline = line.rstrip()
mprev = exists_re.search(currline)
if(mprev):
xlogtime = mprev.group(1)
mcurr = location_re.search(currline)
if(mcurr):
print fn, xlogtime, mcurr.group(1)
Perl版:
#!/usr/bin/perl
while (<>) {
chomp;
if (m/^(.*?) INFO.*Such a record already exists/i) {
$xlogtime = $1;
}
if (m/^AwbLocation (.*?) insert into/i) {
print "$ARGV $xlogtime $1\n";
}
}
time process_file.py *log > summarypy.log
real 0m8.185s
user 0m8.018s
sys 0m0.092s
time process_file.pl *log > summaypl.log
real 0m1.481s
user 0m1.294s
sys 0m0.124s
在文本處理方面,Perl 比Python快8倍左右。
所以在處理大文件如大日志方面,用perl更好,因為更快。
如果對速度要求不是很嚴格的話,用python更好,因為python簡潔易懂,容易維護和閱讀。
為什么在文本處理時,Perl比Python快很多呢?
這是因為Perl的模式匹配是其內置功能,而Python需要加載re模塊,使用內置命令比外部命令要快很多。
內置命令和外部命令的區別
Linux命令有內置命令和外部命令之分,功能基本相同,但是調用有些細微差別。
內置命令實際上是shell程序的一部分,其中包含的是一些簡單的linux系統命令,這些命令在shell程序識別并在shell程序內部完成運行,通常在linux系統加載運行時shell就被加載并駐留在系統內存中。內部命令是設在bash源代碼里面的,其執行速度比外部命令快,因為解析內部命令shell不需要創建子進程,比如exit,cd,pwd,echo,history等。
外部命令是linux系統中的實用應用程序,因為實用程序的功能通常比較強大,其包含的程序量也很大,在系統加載的時候并不隨系統一起被加載到內存中,而是在需要的時候才將其調入內存。通常外部命令的實體并不包含在shell中,但是其命令執行過程是由shell程序控制的。shell程序管理外部命令執行的路徑查找,加載存放,并控制命令的執行。外部命令是在bash之外額外安裝的,通常放在/bin, /usr/bin, /sbin, /usr/sbin,....等。
用type命令可以分辨內部命令與外部命令。

posted on 2015-11-26 23:15
xzc 閱讀(1576)
評論(0) 編輯 收藏 所屬分類:
linux/unix