Learning Perl Chapter 4 exercise questions

Source: Internet
Author: User

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 ");

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.