Perl的数组与hash表使用的对比

比如,你需要从一个文件或者是从console输入一堆单词,你需要查看这堆单词里某些你需要的单词们出现了次数。我分别用数组和hash表来处理这种情况:我假设我是从console输入一堆单词的,并且我需要查出首字母大写的单词

 

数组版:

#!/usr/bin/perl -w use strict; while(my $var = <STDIN>){ my @wordlist = (); my @wordcount = (); my $flg; my $index = 0; while ($var =~ //b[A-Z]/S+/g){ my $word = $&; $word =~ s/[:.,:-]$//; $flg = 0; for(my $count = 1; $count <= @wordlist; $count++){ if($word eq $wordlist[$count-1]){ $flg = 1; $wordcount[$count-1] += 1; last; } } if(!$flg){ $wordcount[$index] = 1; push(@wordlist,$word); $index++; } } for(my $count = 1; $count <= @wordlist; $count++){ print "$wordlist[$count-1]: "; print "$wordcount[$count-1]/n" } }

 

其中 正则表达式 //b[A-Z]/S+/g 是匹配首字母大写的单词,我分别声明了两个数组:一个存放单词,一个存放该单词的次数,如果遇到了新的单词就忘这个单词的list添加,如果是旧的单词则要加1。比较麻烦的是,每次遇到一个单词,都需要循环存放单词的list,来判断是新的还是旧的,所以随着需要的越来越多,那效率也会降低。

 

下面是hash表版:

#!/usr/bin/perl -w use strict; while(my $var = <STDIN>){ my %wordlist; my @wordcount = (); my $flg; my $index = 0; while ($var =~ //b[A-Z]/S+/g){ my $word = $&; $word =~ s/[:.,:-]$//; $wordlist{$word} += 1; } print ("Capitalized words and number of occurrences:/n"); foreach my $capword (keys(%wordlist)) { print ("$capword: $wordlist{$capword}/n"); } }

 

在这里,我们将匹配到的单词作为hash表的key,而他出现的次数作为value。特别的方便,代码量也少了好多,效率也高。

 

你可能感兴趣的:(正则表达式,list,perl)