1 A first example "Hello World"

#!/usr/local/bin/perl -w
# This program says "hello" to the world
print "Hello World!\n";

Copy the blue text from the screen and paste it into a file. Save the file, for example, under the name "hello". Then type at the Unix prompt:

perl hello

1.1 Explanations

# indicates a comment; the line is ignored
print a command; prints the string between the quotes
\n newline character
; indicates the end of a command

1.2 Exercises

* Add a second print statement to the script from the example. (For example print "How are you?".) What does adding or deleting "\n" change?

2 A second example

#!/usr/local/bin/perl -w
# A program for greeting people
print "What is your name? ";
$name = <STDIN> ;
chomp ($name);
print "Hello, $name! How are you?\n";

2.1 Explanations

$name a variable for a "name"
= an assignment operator
<STDIN> reads from standard input (i.e. keyboard)
chomp deletes the newline character ("enter" key)

2.2 Exercises

* What happens if you delete the line with "chomp"?
* Write a program that asks two people for their names; stores the names in variables called $name1 and $name2; says hello to both of them.

3 Operators for Numbers

$a = 3 -4 +10;
$b = 5*6;
$c = 7/8;
print "These are the values: $a $b $c \n";
print "Increment $a by one: ";
print $a;
print "\n";
print "Decrease $a by one: ";
print $a;
print "\n";

3.1 Exercises

* Execute the script. Make sure you understand every line.

3.2 Example

#!/usr/local/bin/perl -w
# This program converts from US $ to Canadian $
print "Money value in US \$ ";
$us_money = <STDIN> ;
chomp $us_money;
$can_money = $us_money /0.6;
print "US\$ $us_money = Canadian \$ $can_money\n";

3.3 Exercises

* In analogy to the example, write a script that asks users for the temperature in F and prints the temperature in C. (Conversion: Celsius = (F - 32) * 5/9 )

4 Strings

A string is delimited by double quotes (""). Certain special characters can be used, such as "\n" and "\t". Variables are interpreted, i.e. 'print "$name"' prints the value of '$name' and not $-sign followed by 'name'. To print the characters $, ", \, @, they must be preceded by a backslash (\).

print "hello\n";
print "hello\\n";
print "\$5.00\n";
print "She said: \"hello\"\n";
print "\tThis is indented\n";
$a = "apples"; $b = "pears";
print "$a and $b\n";

4.1 Exercises

* Write Perl print statements for the following text (with the same linebreaks, etc):

Snoopy bought a CD called "Greatest Hits" on the WWW for
$10.00. To buy the CD he had to send an email message to
orders@hits-online.net. This is what the design on the CD
cover looked like:

       \  |  /
         @ @

4.2 Operators and functions for strings

chop $a; # removes the last character
chomp $a; # removes the last character if it is a newline character
$a = $b . $c; # concatenate $b and $c
$a = $b x $c; # $b repeated $c times

4.3 Example

#!/usr/local/bin/perl -w
# program that demonstrates operating with strings
print "Please, type your favorite color: ";
$color= <STDIN>;
chomp $color;
$color = $color . "***";
chop $color; chop $color;
$color = $color . "!";
$color = $color x 5;
print "$color\n";

(If you are unsure what this program does, add 'print "$color\n";' after every line so that you can see how the content of the variable is changed at each step.)

5 Logical expressions

#!/usr/local/bin/perl -w
# if statement
print "Input first value:";
$a = <STDIN> ;
chomp $a;
print "Input second value:";
$b = <STDIN> ;
chomp $b;
if ($a and $b){
      print "True\n";
} else {
      print "False\n";

5.2 Exercises

* Write a script that asks someone to input their first name, last name and phone number. If the user does not type at least some characters for each of these, print "Do not leave any fields empty" otherwise print "Thank you". (Hint: if a variable is empty, its value will be "false".)

5.3 Other logical expressions for if statements

$a eq $b # Is $a equal to $b?
$a ne $b # Is $a not equal to $b?
$a == $b # Is $a numerically equal to $b?
$a != $b # Is $a numerically unequal to $b?
$a <= $b # Is $a smaller or equal to $b?
$a >= $b # Is $a larger or equal to $b?
$a < $b # Is $a smaller than $b?
$a > $b # Is $a larger than $b?
$a le $b # Does $a come before $b in the alphabet or is equal to $b?
$a ge $b # Does $a come after $b in the alphabet or is equal to $b?
$a lt $b # Does $a come before $b in the alphabet?
$a gt $b # Does $a come after $b in the alphabet?

Note: usually "eq" and "ne" work even for numbers. So, you can use them instead of "==" and "!=".

5.4 Exercises

* Write a program that asks a user to input a color. If the color is black or white, output "The color was black or white". If it starts with a letter that comes after "k" in the alphabet, output "The color starts with a letter that comes after "k" in the alphabet".

6 Control structures: if

#!/usr/local/bin/perl -w
# if statement
print "Do you like Perl? ";
$answer = <STDIN>;
chomp $answer;
if ($answer eq "yes"){
      print "That is great!\n";
} else {
      print "That is disappointing!\n";

6.1 Exercises

5) Modify the program so that it answers "That is great!" if the answer was "yes", "That is disappointing" if the answer was "no" and "That is not an answer to my question." otherwise. Use "if ... elsif ... else ...". Note that "if" and "elsif" are followed by an expression in parenthesis () and then a statement in curly brackets {}, "else" is followed only by a statement in curly brackets.

6.2 While

#!/usr/local/bin/perl -w
# while statement
$answer = "no";
while ($answer ne "yes"){
   print "Do you like Perl? ";
   $answer = <STDIN>;
   chomp $answer;
   if ($answer eq "yes") {
      print "That is great!\n";
   } else {
     print "That is not the right answer! Try again.\n";

6.3 Exercises

* Modify the program from above so that it asks users to "guess the lucky number". If the correct number is guessed the program stops, otherwise it continues forever.

6.4 Using a counter

* Write a program that asks five times to guess the lucky number. Use a while loop and a counter, such as

$counter = 1;
while ($counter <= 5) {
   print "Type in the $counter number\n";

The program asks for five guesses (no matter whether the correct number was guessed or not). If the correct number is guessed, the program outputs "Good guess!\n", otherwise it outputs "Try again!\n". After the fifth guess it stops and prints "Game over.\n".

6.5 Last

* In the previous example, insert "last;" after the "Good guess!\n" print statement. "last" will terminate the while loop so that users do not have to continue guessing after they found the number.

7 Arrays

Arrays in Perl are lists. It should be noted that arrays in PHP correspond to hashs in Perl, which are lists of index/value or key/value pairs. Hashs are also called "associative arrays", "maps", "lookup tables" or "dictionaries".

#!/usr/local/bin/perl -w
# animals in a zoo
@zoo=("monkey", "tiger", "eagle");
print "The zoo has the following ".@zoo." animals: @zoo\n";
print "Which animal would you like to add? ";
$new_animal = <STDIN> ;
chomp $new_animal;
push(@zoo, $new_animal);
$length = @zoo;
print "The zoo now has the following $length animals: @zoo\n";
print "The 3rd animal in the list is $zoo[2]\n";

7.1 Array operators and functions

@zoo = ("monkey", "tiger", "eagle");defining an array
push(@zoo,"parrot"); add elements at end of array
@zoo = ("zebra","lion", @zoo);add elements at beginning
$length = @zoo; length of @zoo
$animal = $zoo[0]; the first element of @zoo
$animal = $zoo[2]; the third element of @zoo
$animal = $zoo[@zoo-1]; the last element of @zoo
$lastelement = pop(@zoo); remove last element from @zoo
@other_zoo = reverse(@zoo); new array with reverse order
@other_zoo = sort(@zoo); new array in alphabetical order

7.2 Exercises

* Create an array that contains the names of 5 students of this class. (You don't need a loop to do that. Simply assign the 5 values.) Print the array. Remove (pop) the last name from the array. Print the array. Ask a user to type in her/his name. Add (push) that name to the array. Print the array. Ask a user to input a number. Print the name that has that number as index. Add "John Smith" and "Mary Miller" at the beginning of the array. Print the array. Print the array in alphabetical and in reverse order.

8 Foreach

#!/usr/local/bin/perl -w
# if statement
@zoo = ("tiger", "elephant", "monkey");
foreach $animal (@zoo){
    $animal = "_".$animal."_";
    print "$animal";
print "\n";

8.1 Exercises

* Create a second copy of the array in reverse order. Add a second foreach loop that prints the reverse copy.

9 Input from a file

Click here and save the file in your current directory under the name "alice.txt".

# Program to read and print a file
open(ALICE, "alice.txt");
@lines = <ALICE> ;
print @lines;

9.1 File handling

open(FILEHANDLE, "alice.txt");
open(FILEHANDLE, "<alice.txt");
open for input
open(FILEHANDLE, ">alice.txt"); open for output
open(FILEHANDLE, ">>alice.txt"); open for appending
print FILEHANDLE "Some text.\n"; print to an open file
open(FILEHANDLE, "alice.txt") || die "cannot open file"; open file, print error message

9.2 Exercises

* Modify the program so that the lines are printed in reverse order.

* Write a Perl script that copies one file to another file. Then change the script so that it appends one file to another file.