Sie sind auf Seite 1von 6

Programming 101 Series

Perl String Manipulation


Exercise Answers

Mark Travnikoff

Perl: String Manipulation


Exercise Answers
1. Using the following array: @array = (arent, you, HAPPY?);
Write a script to print out the following line including the quote marks: Arent YOU
Happy?

#!/usr/intel/bin/perl
@array = ("aren't", "you", "HAPPY?");
print "\"\u$array[0]\E \U$array[1]\E \L\u$array[2]\"\n";

2. What do the following lines print out:


print q(Arent you done yet?\n); => Aren't you done yet?\n
print qq(I am bored\b\b\b\b\bhappy!\n); => I am happy!

Perl: String Manipulation


Exercise Answers
3. Write the script on slide #20, but remove the chomp commands in order to see the effects
of not chomping user inputted data.

#!/usr/intel/bin/perl

print "What is your name? ";


$name = <STDIN>;
print "What month were you born in? ";
$month = <STDIN>;
@data = (@data, $month); # Place input at end of array.
print "What year were you born in? ";
@data = (@data, $year = <STDIN>); # Place input at end of array.

print "$name was born in $data[0] in $data[1].\n";

Perl: String Manipulation


Exercise Answers
4. Write a script that outputs the truth table of a 3-input AND gate. Use the printf function to
create formatted output similar to the that shown below. Each input/output column should be
left justified & have a field width of 5 spaces.
IN1 IN2 IN3 OUT
-------------------------
0 0 0 0
0 0 1 0
0 1 0 0

#!/usr/intel/bin/perl
printf "%-5s%-5s%-5s%-5s\n", "IN1", "IN2", "IN3", "OUT";
print "-" x 18 . "\n";
printf "%-5d%-5d%-5d%-5d\n", 0, 0, 0, 0;
printf "%-5d%-5d%-5d%-5d\n", 0, 0, 1, 0;
printf "%-5d%-5d%-5d%-5d\n", 0, 1, 0, 0;
printf "%-5d%-5d%-5d%-5d\n", 0, 1, 1, 0;
printf "%-5d%-5d%-5d%-5d\n", 1, 0, 0, 0;
printf "%-5d%-5d%-5d%-5d\n", 1, 0, 1, 0;
printf "%-5d%-5d%-5d%-5d\n", 1, 1, 0, 0;
printf "%-5d%-5d%-5d%-5d\n", 1, 1, 1, 1;

Perl: String Manipulation


Exercise Answers
5. Modify the program from the Perl: Basics exercises, which computes the total resistance
of three resistors in parallel, so that the outputted total resistance is rounded to 2 decimal
places.
RT = 1/[(1/R1) + (1/R2) + (1/R3)]

#!/usr/intel/bin/perl
print "Enter first resistor value: ";
$first = <STDIN>;
print "Enter second resistor value: ";
$second = <STDIN>;
print "Enter third resistor value: ";
$third = <STDIN>;

$total = 1/((1/$first) + (1/$second) + (1/$third));


printf "\nTotal Resistance: %.2f\n", $total;

Perl: String Manipulation


Exercise Answers
6. Write a program that computes and outputs the circumference of a sphere (2r). Prompt
the user for the radius. Use 3.141592654 for the value of pi. Round to four decimal places.

#!/usr/intel/bin/perl

$pi = 3.141592654;
print "What is the radius: ";
chomp($radius = <STDIN>); # Grab radius & chomp.
$result = 2 * $pi * $radius; # Calculate circumference.
printf "Circumference: %.4f\n", $result;

Perl: String Manipulation

Das könnte Ihnen auch gefallen