Learning Perl Chapter 1 exercise

Source: Internet
Author: User

Posted on Netease blog 13:10:11

1st print the last name based on the entered person name

#! 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 ";
}
2nd print the number of words entered

#! Perl-W
Use strict;
My % wordcounter;
My $ word;
# While (Chomp ($ word = <stdin>) will report an error saying that an uninitialized $ word value is used.
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 ";
}

3rd question print system environment variables

#! 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 is a regular function, so you do not need to use the & length ($ _) method when calling it.
$ Key_len = length ($ _);
}
}
My $ format = "%-$ {key_len} s \ t % s \ n ";
Foreach (@ keys ){
Printf $ format, "$ _", "$ ENV {$ _}";
}

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.