原文发表在网易博客 2010-11-06 13:07:36 第1题和第2题 #!perl -w #chapter 4 , exercise one and two use strict; sub total{ my $sum; foreach $_ (@_){ $sum += $_; } $sum; } my @fred=(1,3,5,7,9); print "sum of (@fred) is:\t ",&total(@fred),"\n"; print "sum of 1 to 100 is :\t",&total(1..100),"\n"; 第3题 #!perl -w #chapter 4 , exercise 3 use strict; sub getSum{ my $sum=0; foreach $_ (@_){ $sum+=$_; } $sum; } sub getAverage{ my @abovelist=(); my $length=@_; my $average=-1; $average=&getSum(@_)/$length; } sub above_average{ my @abovelist; my $average=&getAverage(@_); foreach $_ (@_){ if($_ > $average){ push @abovelist, $_ } } return @abovelist; } my @fred=&above_average(1..10); print "above the average in one to ten is :(@fred)\n"; 第4题 #!perl -w use strict; use 5.010; sub greet1{ state $lastPerson=""; if(@_ ==1 ){ if($lastPerson ne ""){ print "Hi,$_[0]!$lastPerson is also here.\n"; }else{ print "Hi,$_[0]!You are the first one here!\n"; } $lastPerson=$_[0]; } } &greet1("leipei"); &greet1("ada"); 第5题 #!perl -w use strict; use 5.010; sub greet2{ state @personlist; if(@_ == 1){ if(@personlist >0){ print "Hi,$_[0]! I have seen:@personlist\n"; }else{ print "Hi,$_[0]! You are the firt one here.\n"; } push (@personlist,$_[0]); } } greet2("Fred"); greet2("Barney"); greet2("Wilma"); greet2("Betty");
|
请发表评论