[perl] 不知道陣列該多大時的小技巧

寫文字處理程式總會遇到一些小問題,例如對於不知道字頻範圍,卻又想要記錄下來,許多時候就不知不覺變成寫死的程式碼,指定要記錄那些範圍的頻率。
這是原先的程式碼:

my $count = 0;
my $count2 = 0;
my $count3 = 0;
my $count4 = 0;
my $count5 = 0;
my $count6 = 0;
my $count7 = 0;
my $count8 = 0;
my $count9 = 0;
my $count10 = 0;
my $count11 = 0;
for my $word (keys %word_tag) {
# at least one tag and one COUNT
$count11++ if (keys %{$word_tag{$word}}) == 12;
$count10++ if (keys %{$word_tag{$word}}) == 11;
$count9++ if (keys %{$word_tag{$word}}) == 10;
$count8++ if (keys %{$word_tag{$word}}) == 9;
$count7++ if (keys %{$word_tag{$word}}) == 8;
$count6++ if (keys %{$word_tag{$word}}) == 7;
$count5++ if (keys %{$word_tag{$word}}) == 6;
$count4++ if (keys %{$word_tag{$word}}) == 5;
$count3++ if (keys %{$word_tag{$word}}) == 4;
$count2++ if (keys %{$word_tag{$word}}) == 3;

}

然後之後再一個一個輸出,現在改寫成讓它自己生 :oops:

my @counts;
for my $word (keys %word_tag) {
$counts[(keys %{$word_tag{$word}})-1]++; # at least one tag and one COUNT

}
for my $i (1..$#counts) {
print “$i Tag words is “.$counts[$i].”n”;
}

其實可以再簡潔一點,不過我覺得這樣就很夠了 :p

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • funp
  • Haohao
  • Hemidemi
  • Live
  • MisterWong
  • TwitThis
  • udn
 

Other posts

One reply


  1. 看了半天也不知道你干吗啊?

Leave a reply

Creative Commons Attribution-NonCommercial-ShareAlike 2.5 Taiwan
Creative Commons Attribution-NonCommercial-ShareAlike 2.5 Taiwan