今天粗略看了下《Perl 高效编程》,觉得是本好书。学到了一些之前没有见过的小技巧。
1.perl里的switch:given () when {}
- a.
-
given ($var) {
-
when('a') { do sth1}
-
when('b') {do sth2}
-
when('c') {do sth3}
-
default { do default thing};
-
};
-
-
b.
-
given ($dog) {
-
when ($dog eq 'a') {do sth1}
-
when ($dog eq 'b') {do sth2}
-
default (do default thing);
-
};
-
-
b.
-
given ($dog) {
-
when($dog ~~ 'a') {do sth1}
-
when($dog ~~ 'b') {so sth2}
-
default (do default thing);
-
-
};
2.智能匹配
3.只编译一次正则表达式和预编译正则表达式
加 'o' 标志,如if ($line=~/\d{3,}/o )则正则表达式只编译一次
使用 qr则可以预编译正则表达式
4.哈希的切片,删除
- #!/usr/bin/perl -w
-
use strict;
-
my %hash=(
-
'a'=>1,
-
'b'=>2,
-
'c'=>3,
-
'd'=>4,
-
'e'=>5,
-
);
-
-
&phash(\%hash);
-
my @del=('a','b','e');
-
delete @hash{@del};
-
print "after delete :\n",join("\n",@del),"\n";
-
&phash(\%hash);
-
sub phash(\%) {
-
my $href=shift;
-
while (my ($k,$v)=each %{ $href }) {
-
print $k,'==>',$v,"\n";
-
}
-
-
}
-
gnu@debian:~$ ./hash.pl
-
e==>5
-
c==>3
-
a==>1
-
b==>2
-
d==>4
-
after delete :
-
a
-
b
-
e
-
c==>3
-
d==>4
阅读(912) | 评论(0) | 转发(0) |