Solutions# 1

advertisement
Perl Assignments (chapters 1-3)
1. Write a program that computes the circumference of a circle. The user can
enter the radius from the command line. (Hint: Circumference = 2PI times
the radius)
#!/usr/bin/perl
#
use strict;
use warnings;
print "enter the size of the radius =";
chomp (my $r=<STDIN>);
my $circumference = 3.14159 * $r;
print "the circumference of a radius of size $r is equal to
$circumference\n";
2. Write a program that prompts for an reads two numbers (on separate lines
of input) and prints out the product of the two numbers multiplied together.
use strict;
use warnings;
print "enter the first number =";
chomp (my $r1=<STDIN>);
print "enter the second number =";
chomp (my $r2=<STDIN>);
print "the multiplication of $r1 by $r2 is equal to
($r1*$r2)\n";
3. Write a program that prompts for and reads a string and a number (on
separate lines of input) and prints out the string the number of times
indicated by the number on separate line. (Hint: use the operator x)
use strict;
use warnings;
print "enter a string =";
chomp (my $r1=<STDIN>);
print "enter a number =";
chomp (my $r2=<STDIN>);
my $result = $r1 x $r2;
print $result;
4. Write a program that reads a list of strings on separate lines until end-ofinput and prints out the list in reverse order. If the input comes from the
keyboard, you’ll probably need to signal the end of input by pressing ControlD on Mac or Control-Z on Windows.
use strict;
use warnings;
print "enter one string at each line:";
my $line;
my @string= ();
while ($line = (<>)) {
chomp ($line);
@string = (@string , $line);
}
@string = reverse @string;
print @string;
5. Write a program that reads a list of numbers (on separate lines) until end-ofinput and then prints for each number the corresponding person’s name
from the list shown below. (Hardcode this list of names into your program.
That is, it should appear in your program’s source code.) For example, if the
input numbers were 1,2,4, and 2, the output names would be fred, betty,
dino, and betty.
Fred betty barney dino Wilma pebbles bamm-bamm
use strict;
use warnings;
print "enter one string at each line:";
my %names = (1, "fred" , 2, "betty", 3 ,"dino", 4,
"wilma", 5, "pebbles", 6, "bammbamm" );
my $number;
my @temp = ();
while ($number = <>){
chomp($number);
if ($number < 1 or $number >6){
@temp = (@temp, "out of range");
}else {
@temp = (@temp, $names{$number});
}
}
print @temp;
6. Write a program that reads a list of strings (on separate lines) until end-ofinput. Then it should print the strings in ASCIIbetical order. That is, if you
enter the strings fred, barney, Wilma, betty, the output should show barney
betty fred Wilma.
use strict;
use warnings;
print "enter one string at each line:";
my $line;
my @array=();
while ($line = <>) {
chomp ($line);
@array = (@array, $line);
}
@array = sort @array;
print "@array ";
Download