Basic Perl Exercises
The following mini exercises are designed to help you get a feel what is it like to write Perl program. As described in the lecture, Perl in a way is a “strange” programming language that in some sense is quite different from others. The semantics of Perl can be quite flexible, compact and terse. If unfamiliar, or new to the language, you will find Perl hard to read and at times difficult to understand. As with learning a new language (even for spoken ones), continuous practice will help you to get things going and hopefully to make Perl one of your favourite languages.
- The following program is to enable an administrator to enter a student’s particulars starting from the student id, name and the score obtained for the Internet Computing subject. Once completed, the program allows the administrator to search the score based on student id. Download and study the program carefully to see how associative array can be used to implement efficient database-like functions. Modify the program as follows:
- Entering student id of ‘0’ is invalid. If detected, prompt the user and return to normal function.
- Check that student id entered is unique, i.e. no repeating student id is allowed.
print "Enter student id (or 'bye' to end) ";
while(>){
chomp($_);
if ($_ eq 'bye'){
last;
}
print "Enter student name "; chomp($name=<STDIN>);
print "Enter IC score "; chomp($score=<STDIN>);
print "\n";
$name_list{$_} = $name;
$score_list{$_} = $score;
print "Enter student id (or 'bye' to end) ";
}
print "Enter student id to search (or 'bye' to end) ";
while(>){
chomp($_);
if ($_ eq 'bye'){
last;
}
print "Name ", $name_list{$_}, " ";
print "Score ", $score_list{$_}, "\n";
print "Enter student id to search (or 'bye' to end) ";
}
- In the following exercise, write a program that will prompt the user to enter a word per line, until end-of-file is encountered. Subsequently, the program will compute and print a summary of how many times each word is encountered and the total number of words entered. The display should have the following format (note the words are just examples):
WordCount
Apple5
Orange3
Kid5
Total13
Below is a possible program structure. Fill in the missing ?
chomp(@words = <????>); #chomp to remove newline
$total_count = 0;
foreach $word(?words){ #routine to compute number of words
$count{$????} = ????+1;
$total_count++;
}
print "\nWord\tCount\n";
print "----\t-----\n";
foreach $word (keys %count){ #routine to display result
print $word, "\t", $????, "\n";
}
print "Total\t", $????, "\n";
3.Suppose the variable $var has the value abc123abc. What is the value of $var after the following substitutions?
a. $var =~ s/abc/def/;
b. $var =~ s/[a-z]+/X/g;
c. $var =~ s/B/W/i;
d. $var =~ s/(.)\d.*\1/d/;
e. $var =~ s/(\d+)/$1*2/e;