Perl是什么?用Larry Wall自己的话说,Perl是借取了C、sed、awk、shell scripting以及很多其他程序语言的特性的一种语言。你可以说它是“实用报表提取语言”(Practical Extraction and Report Language),也可以叫它“病态折中垃圾列表器”(Pathologically Eclectic Rubbish Lister),Larry说:“OK,我都承认”。
最近机缘巧合,有幸接触了一把Perl,以及它的模板引擎Mason(我是这么理解的)。我用过Java、C#、C++等等传统高级语言,也研究过Groovy、JavaScript之类的动态语言,甚至自虐过VB(Don Box还说了一段很好玩的话,其中的“Dim me As VBProgrammer”流传甚广),我很懒,并不打算仔细研究Perl——有的东西我有兴趣一查到底,有的东西觉得点到即止,够用就好,于是只想粗略地把它过一遍,不过Perl还是立马给我留下了深刻印象。
Martin Fowler提出了两种API风格:最小接口和人本接口,前者简约、干净、独立,接口覆盖功能没有交集,而后者则提供了一大堆人性化的方法,方法之间互有冗余。Perl就像人本接口,用Perl爱好者们自己的话说,叫做“There's More Than One Way To Do It.”,虽然很多动态语言也提供了丰富的方法,但是Perl把这一点做到了极致。
事实上,我在几个月以前就已经写出了一些简单的perl脚本,但是它和Linux的亲和力让它非常好用。那个时候我还几乎不了解Perl,但是我就照着同事的一点Perl代码,加上我自己的理解,去完成了一个在Linux上用的小工具,Perl就是如此具有易上手的特性,连Google的时间都省了。
如果你就这样认为Perl是一个语法简单的语言,那就错了。Perl是一个可以写出极其简练代码的语言(这往往意味着也可以写出极其混乱的代码来,比如这个),但是功能上并不含糊(有一个很著名的Perl项目ppt,用纯perl实现了所有Unix下的常用命令)。另外,Perl大概是最好的对字符串进行处理的语言。
给以文件操作的例子,如果用Java,需要写:
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("test.txt"));
String line = br.readLine();
while (null != line) {
if (line.startsWith("http:"))
System.out.print(line);
line = br.readLine();
}
} catch (FileNotFoundException e) {
System.out.println("Can't open file:" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果用perl,只需要:
open(FILE, "test.txt") or die "Can't open file: $!\n";
while (<FILE>) {
chomp;
print if /^http:/;
}
谈到Perl不能不说其独有的诗歌文化,因为语言的包容性、丰富的表达方式和灵活性,让Perl可以写出诗歌一样的代码。比如这首名为《Black Perl》的Perl诗歌,更多的请到perlmonks去找:
BEFOREHAND: close door, each window & exit; wait until time.
open spellbook, study, read (scan, select, tell us);
write it, print the hex while each watches,
reverse its length, write again;
kill spiders, pop them, chop, split, kill them.
unlink arms, shift, wait & listen (listening, wait),
sort the flock (then, warn the "goats" & kill the "sheep");
kill them, dump qualms, shift moralities,
values aside, each one;
die sheep! die to reverse the system
you accept (reject, respect);
next step,
kill the next sacrifice, each sacrifice,
wait, redo ritual until "all the spirits are pleased";
do it ("as they say").
do it(*everyone***must***participate***in***forbidden**s*e*x*).
return last victim; package body;
exit crypt (time, times & "half a time") & close it,
select (quickly) & warn your next victim;
AFTERWORDS: tell nobody.
wait, wait until time;
wait until next year, next decade;
sleep, sleep, die yourself,
die at last
如果一门语言能给你带来对设计和编码很多新的理解和体验,那么,不妨尝试一下它。
--------------------------------------------------------------------------------------------------------------------------------
2012-5-23:
Perl有一个有名的框架是Mason,perl可以做很多事,脚本、胶水语言等等,Mason则是一个用perl来实现页面模板的好例子。建议对perl有兴趣的同学,关注一下它。另外,不妨再有对比地了解一下Embperl这个框架(它能够对HTML标签具备语义识别的能力,有些奇葩)。 文章系本人原创,转载请注明出处和作者