【IT168 技术文档】perl当然是一门非常棒的语言, 不过它当然也不完美。很多时候,一些很自然的解决方法却不能和它很‘自然’的吻合。有时候你会想,要是让perl按照你的语法来就好了 ;)例如, perl的例程不能指定参数列表一直非议很大,比如你不能这样写:
my @NUMERAL_FOR = (0..9,'A'..'Z'); sub convert_to_base($base, $number) { my $converted = ""; while ($number > 0) { $converted = $NUMERAL_FOR[$number % $base] . $converted; $number = int( $number / $base); } return $converted; }
你只能这样:
sub convert_to_base { my ($base, $number) = @_; # <-- 只能手工指定参数。。。。 my $converted = '' while ($number > 0) { $converted = $NUMERAL_FOR[$number % $base] . $converted; $number = int( $number / $base); } return $converted; }
perl程序员的优点(缺点?)之一就是懒惰,所以很多很多人这样写:
sub convert_to_base { my $converted = ''; while ($_[1] > 0) { $converted = $NUMERAL_FOR[$_[1] % $_[0]] . $converted; $_[1] = int( $_[1] / $_[0]); } return $converted; }
天哪,对于后来的维护人员来说,简直是噩梦!(这个人往往是你自己,不过过了几个月之后,你可能也要重新看代码。)解决方案:perl 并不完美, 不过你可以自己动手让它完美。perl 5.8以后的版本,提供了一种方法,可以在源代码送入编译器以前,用你希望的方式先做某些改变。这里我介绍一种最简单的办法: 用Filter::Simple来写自己的模块以修改perl语法。其实思路很简单,perl编译器只会关心最终送过来的源代码,我们只要使用filter模块把源代码变成编译器能够识别就行了。下面的简单例子,就使perl的例程增加了参数声明功能:
package Sub::With:arams; use Filter::Simple; my $IDENT = qr/[^\\W\\d]\\w*/; FILTER_ONLY code => sub{ s{ ( sub \\s* $IDENT \\s* ) # 例程名 ( \\( .*? \\) ) # 参数列表 ( \\s* \\{ ) # 例程体 } {$1$3 my $2 = \\@_;}gxs; #替换为编译器认识的代码}; 1;
大功告成! 现在你可以高高兴兴的按照下面的方式来写:
use Sub::With:arams; sub convert_to_base($base, $number) { my $converted = ''; while ($number > 0) { $converted = $NUMERAL_FOR[$number % $base] . $converted; $number = int( $number / $base); } return $converted;}
在送到编译器以前,Sub::With:arams 会把你的代码转成以下形式:
sub convert_to_base { my ($base, $number) = @_; my $converted = ''; while ($number > 0) { $converted = $NUMERAL_FOR[$number % $base] . $converted; $number = int( $number / $base); } return $converted;}
怎么样?很简单吧。这是大面先生的优秀作品,也是5.8以后的标准模块。大家可以用perldoc 查看详细用法。