Previous Page Next Page

Chapter 3. Perl Scripts

3.1. Script Setup

A Simple Perl Script

Example 3.1.

(The Script)
#!/usr/bin/perl
print "What is your name? ";
chomp($name = <STDIN>);  # Program waits for user input from keyboard
print "Welcome, $name, are you ready to learn Perl now? ";
chomp($response = <STDIN>);
$response=lc($response);  # response is converted to lowercase
if($response eq "yes" or $response eq "y"){
     print "Great! Let's get started learning Perl by example.\n";
}
else{
   print "O.K. Try again later.\n";
}
$now = localtime;  # Use a Perl function to get the date and time
print "$name, you ran this script on $now.\n";

(Output)
What is your name? Ellie
Welcome, Ellie, are you ready to learn Perl now? yes
Great! Let's get started learning Perl by example.
Ellie, you ran this script on Wed Apr  4 21:53:21 2007.

Example 3.1 is an example of a Perl script. In no time, you will be able to write a similar script. Perl scripts consist of a list of Perl statements and declarations. Statements are terminated with a semicolon (;). (Since only subroutines and report formats require declarations, they will be discussed when those topics are presented.) Variables can be created anywhere in the script and, if not initialized, automatically get a value of 0 or "null," depending on their context. Notice that the variables in this program start with a $. Values such as numbers, strings of text, or the output of functions can be assigned to variables. Different types of variables are preceded by different "funny symbols," as you'll see in Chapter 4.

Perl executes each statement just once, starting from the first to the last line.

Previous Page Next Page