janneyabc 发表于 2015-12-28 11:37:11

Learning perl 第6章习题

  原文发表在网易博客 2010-11-19 13:10:11
  第1题根据输入的人名打印其姓氏
  #!perl -w   
#getfamilyname   
use strict;   
my %nameTable=("fred"=>"flintstone","barney"=>"rubble","wilma"=>"flintstone");   
print "input person name,and the program will print his familyname.\n";   
my $personName=<STDIN>;   
chomp($personName);   
if(exists $nameTable{$personName}){   
print &quot;peron ${personName}'s familyname is $nameTable{$personName}\n&quot;;   
}else{   
print &quot;no such person\n&quot;;   
}   
第2题打印输入的每个单词出现的个数
  #!perl -w   
use strict;   
my %wordCounter;   
my $word;   
#while(chomp($word=<STDIN>))会报错说使用了一个未初始化的$word值   
while($word=<STDIN>){   
chomp($word);   
if(exists $wordCounter{$word}){   
   $wordCounter{$word}+=1;   
}else{   
   $wordCounter{$word}=1;   
   }   
}   
my $key;   
my $value;   
print &quot;print wordCounter without order.\n&quot;;   
while(($key,$value)= each %wordCounter){   
print &quot;$key,\t$value\n&quot;;   
}   
print &quot;print wordCounter with ascii order\n&quot;;   
my @orderdkeys=sort keys %wordCounter;   
foreach(@orderdkeys){   
print &quot;$_,\t$wordCounter{$_}\n&quot;;   
}
  第3题打印系统的环境变量
  #!perl -w   
use strict;   
print &quot;print system ENV with ascii orders\n&quot;;   
my @keys=sort(keys %ENV);   
my $key_len=0;   
foreach(@keys){   
if(length($_)> $key_len){   
#length是常规函数,因此调用时不需要使用&length($_)的方式.   
$key_len=length($_);   
}   
}   
my $format=&quot;%-${key_len}s\t%s\n&quot;;   
foreach(@keys){   
printf $format,&quot;$_&quot;,&quot;$ENV{$_}&quot;;   
}
页: [1]
查看完整版本: Learning perl 第6章习题