Learning perl 第6章習題

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.