这里归纳一下用perl语言编程需要注意的问题。
1. 由于哈希值是没有先后次序的,所以哈希函数返回的值都是经过sort的,而非哈希赋值时的状态。例如:
my %hash2=( 'ten' => 10, 'fiirt' => 1, 'second' => 2, 'third' => 3, 'fouth' => 4); print keys %hash2; ---result----- fiirtsecondthirdfouthten
使用哈希函数each,获得结果也是经过sort的,例如:
my %hash2=( 'ten' => 10, 'fiirt' => 1, 'second' => 2, 'third' => 3, 'fouth' => 4); while (my ($key, $value) = each %hash2) { print "$key => $value\n"; } -----result------ fiirt => 1 second => 2 third => 3 fouth => 4 ten => 10
2. Perl变量、数组变量、哈希变量没有定义和undef的区别。如果没有用my(strict的要求),则不能使用。只有定义了,但没有赋值,其值才为undef。例如在一下例子运行错误。
if (%dfd) { print 'ok';} else { print 'not ok';}
3. 把未定义值当成数字使用时,Perl会自动将它转换成0。如果使用use warnings;use strict。虽然程序会报错,虽然依旧会出结果。
print 12*$a; ------result------- Name "main::a" used only once: possible typo at ts2.pl line 19. Use of uninitialized value $a in multiplication (*) at ts2.pl line 19. 0[nan@localhost pl]$ fg
4.<>在读取文件的时候,在最后一行读完后,会返回undef值,其目的是为了结束循环之用。例如:
open FILE, "<tt.pl" or die "the file tt.pl can not be opened $!"; while(<FILE>) { print; }
但是,在<STDIN>从键盘读取数据的时候,如果使用while循环,则无法跳出循环,所以最好设置一个跳出循环的特殊字符。例如:
while (<>) { last if (/^EOF$/); print; }
5. reverse使用在哈希值的时候,如果value的值相同,那么key<->value翻转后,保留第一个,往后相同的会被全部删除。例如:
6 my %h = ( 'a'=>'1', 'b'=>'1', 'c'=>'3', 'd'=>'4' ); 7 8 my %b=reverse %h; 9 10 while (my ($key, $value) = each %h) { 11 print "$key => $value\n"; 12 } 13 print "\n"; 14 while (my ($key, $value) = each %b) { 15 print "$key => $value\n"; 16 } [nan@localhost pl]$ perl s.pl c => 3 a => 1 b => 1 d => 4 1 => a 4 => d 3 => c
6. print可以打印数组和哈希值。结果是不留空格的值(哈希值是KEYVALUE...)。
7. Perl的自增、自减。针对含有字符的变量自增和自减,会按照ASCII字符集变更。例如:
my $a='a'; print ++$a; b[nan@localhost pl]$
8. -s/-z 对文件的判断操作。对软连接也适用。不仅如此,除判断特定类型的文件,或者目录和文件的option之外,不会判断文件是否是软连接或者真实的文件。例如:
print 'a file' if (-e 'tts.pl'); #-----result------- #a file print 'a file' if (-f 'tts.pl'); #-----result------ #a file # print 'a file' if (-l 'tts.pl'); #-----result------ #a file