原文發表在網易部落格 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{$_}";
}