原文发表在网易博客 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 "peron ${personName}'s familyname is $nameTable{$personName}\n";
}else{
print "no such person\n";
}
第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 "print wordCounter without order.\n";
while(($key,$value)= each %wordCounter){
print "$key,\t$value\n";
}
print "print wordCounter with ascii order\n";
my @orderdkeys=sort keys %wordCounter;
foreach(@orderdkeys){
print "$_,\t$wordCounter{$_}\n";
}
第3题打印系统的环境变量
#!perl -w
use strict;
print "print system ENV with ascii orders\n";
my @keys=sort(keys %ENV);
my $key_len=0;
foreach(@keys){
if(length($_)> $key_len){
#length是常规函数,因此调用时不需要使用&length($_)的方式.
$key_len=length($_);
}
}
my $format="%-${key_len}s\t%s\n";
foreach(@keys){
printf $format,"$_","$ENV{$_}";
}