Perl Programming/Exercise 1

From Wikibooks, open books for an open world
< Perl Programming
Jump to: navigation, search

A. Getting started, displaying text[edit]

Task: Create a Perl program which displays "Hello world" and then exits.

# !/usr/bin/perl
 
#helloWorld.pl
 
#Program to display "Hello world"
 
print "Hello world";
 
#End of program.

B. Displaying numbers[edit]

i) Put the number 4000/7 into a variable, and display it on screen.

ii) Adapt the program to display the number to 3 decimal places. (Hint: This is possible using integer math before the final calculation.)

iii) Adapt the program to round up if the last decimal place is greater than 5

iv) Adapt the program to display the number with leading zeros

v) Adapt the program to show a + sign if the number is positive, and check that it correctly displays a - sign if you subtract 1000 from the number.

#!/user/bin/perl
 
#displayNumberOnScreen.pl
 
$divisionResult = 4000/7;
print "Result of 4000 divided by 7 is $divisionResult";

C. Functions[edit]

Write a function to calculate the roots of a quadratic equation, where you give the coefficients a,b,c to the function, and it returns both values of x

D. Putting it all together[edit]

Put together these programs into one which:

  • Displays a title on screen
  • Creates 3 random numbers (a,b,c)
  • Displays those numbers neatly formatted
  • Uses those numbers as the coefficients of a quadratic equation, calculates and displays both roots.


Answers

Next exercise