http://www.unix.com.ua/orelly/perl/cookbook/ch08_03.htm
如果要用perl来查一个文件有多少行,怎么办?Perl Cookbook里的Counting Lines (or Paragraphs or Records) in a File就给我们讲了一些方法。
在windows下,可以配合Cygwin里的wc来得到结果。如果你的Cygwin里已经装了wc,则直接用下面的程序就可以得到你想要的结果: $count = `wc -l < $file`; die "wc failed: $?" if $?; chomp($count);
当然,如果你喜欢的话,也可以直接打开文件,一行一行地读入文件,然后得到文件的行数。 open(FILE, "< $file") or die "can't open $file: $!"; $count++ while <FILE>; # $count now holds the number of lines read
如果你的行是以“\n”结尾的话,可以这样写: $count += tr/\n/\n/ while sysread(FILE, $_, 2 ** 16);
当然,你也可以模拟wc的形式来写这些代码,下面就是一种形式: open(FILE, "< $file") or die "can't open $file: $!"; $count++ while <FILE>; # $count now holds the number of lines read
更加简洁的形式: open(FILE, "< $file") or die "can't open $file: $!"; for ($count=0; <FILE>; $count++) { }
还有一种更酷的写法: 1 while <FILE>; $count = $.;
如果你要数一数有多少个段落,就参考这个代码吧: $/ = ''; # enable paragraph mode for all reads open(FILE, $file) or die "can't open $file: $!"; 1 while <FILE>; $para_count = $.;
我给别人培训用的ppt
创建新Module的简明教程,http://perldoc.perl.org/perlnewmod.html
How to write CPAN module,关于如何写CPAN module。