Posted on Netease blog 13:07:36
1st and 2nd
#! 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 ";
3rd questions
#! 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 ";
4th questions
#! 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 ");
5th questions
#! 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 ");