Go to the first, previous, next, last section, table of contents.

Getting Started

This chapter begins the introduction to Perl by giving a simple code example. We do not expect the reader to understand this example completely (yet). We present this example to ease the reader into Perl's syntax and semantics.

A First Perl Program

So, to begin our study of Perl, let us consider a small Perl program. Do not worry that you are not familiar with all the syntax used here. The syntax will be introduced more formally as we continue on through this book. Just try to infer the behavior of the constructs below as best you can.

For our first Perl program, we will ask the user their username, and print out a message greeting the user by name.


use strict;                        # @cc{important pragma}
use warnings;                      # @cc{another important pragma}
print "What is your username?  ";  # @cc{print out the question}
my $username;                      # @cc{``declare'' the variable}
$username = <STDIN>;               # @cc{ask for the username}
chomp($username);                  # @cc{remove ``new line''}
print "Hello, $username.\n";       # @cc{print out the greeting}

# @cc{Now we have said hello to our user}

Let us examine this program line by line to ascertain its meaning. Some hand-waving will be necessary, since some of the concepts will not be presented until later. However, this code is simple enough that you need not yet understand completely what each line is doing.

The first line is how the program is identified as a Perl program. All Perl programs should start with a line like #!/path/perl. Usually, it is just #!/usr/bin/perl. You should put this line at the top of each of your Perl programs.

In the lines that follow, halfway through each line, there is a `#' character. Everything from the `#' character until the end of the line is considered a comment. You are not required to comment each line. In fact, commenting each line is rare. However, you will find in this text that we frequently put comments on every line, since we are trying to explain to the reader exactly what each Perl statement is doing. When you write Perl programs, you should provide comments, but you need not do so as verbosely as we do in this text.

Note, too, that comments can also occur on lines by themselves. The last line of the program above is an example of that.

Now, consider the code itself, ignoring everything that follows a `#' character. Notice that each line (ignoring comments) ends with a `;'. This is the way that you tell Perl that a statement is complete. We'll talk more about statements soon; for now, just consider a statement to be a single, logical command that you give to Perl.

The first line, use strict, is called a pragma in Perl. It is not something that "explicitly" gets executed, from your point of view as the programmer. Instead, a pragma specifies (or changes) the rules that Perl uses to understand the code that follows. The use strict; pragma enforces the strictest possible rules for compiling the code. You should always use this pragma while you are still new to Perl, as it will help you find the errors in your code more easily.

The second line is another pragma, use warnings. This pragma tells Perl that you'd like to be warned as much as possible when you write code that might be questionable. Certain features of Perl can confuse new (and sometimes even seasoned) Perl programmers. The use warnings pragma, like use strict, is a way to tell Perl that you'd like to be warned at run-time when certain operations seem questionable.

So, you might wonder why two separate pragmas are needed. The reason is that they are enforced by Perl at different times. The use strict pragma enforces compile-time constraints on the program source code. You can even test them without running the program by using perl -c filename, where filename is the file containing your program. That option does not run your program, it merely checks that they syntax of your program is correct. (To remember this, remember that the letter `c' in @option{-c} stands for "check the program".)

By contrast, the use warnings pragma controls run-time behavior. With use warnings, messages could be printed while your program runs, if Perl notices something wrong. In addition, different inputs to the program can cause different messages to be printed (or suppress such messages entirely).

The third line is the first statement of the program the performs an action directly. It is a call to Perl's built-in @builtin{print} function. In this case, it is taking a string (enclosed in double quotes) as its argument, and sending that string to the standard output, which is, by default, the terminal, window, or console from which the program is run.

The next line is a variable declaration. When in @module{strict} mode (set by the use strict pragma), all variables must be declared. In this case, Perl's @keyword{my} keyword is used to declare the variable @scalar{$username}. A variable like @scalar{$username} that starts with a $ is said to be a scalar variable. For more information on scalar variables, see section Working with Scalars. For now, just be aware that scalar variables can hold strings.

The next line, $username = <STDIN> is an assignment statement, which is denoted by the =. The left hand side of the assignment is that scalar variable, @scalar{$username}, that we declared in the line before it. Since @scalar{$username} is on the left hand side of the =, that indicates @scalar{$username} will be assigned a new value by this assignment statement.

The right hand side of the assignment is a construct that allows us to get input from the keyboard, the default standard input. @fileh{STDIN} is called a file handle that represents the standard input. We will discuss more about file handles later. For now, just remember that the construct <STDIN>, when assigned to a scalar variable, places the next line of standard input into that scalar variable.

Thus, at this point, we have the next line of the input (which is hopefully the username that we asked for), in the @scalar{$username} variable. Since we got the contents of @scalar{$username} from the standard input, we know that the user hit return after typing her username. The return key inserts a special character, called newline, at the end of the line. The @scalar{$username} variable contains the full contents of the line, which is not just the user's name, but also that newline character.

To take care of this, the next thing we do is chomp($username). Perl's built-in function, @builtin{chomp}, removes any newline characters that are on the end of a variable. So, after the @builtin{chomp} operation, the variable @scalar{$username}

The final statement is another @builtin{print} statement. It uses the value of the @scalar{$username} variable to greet the user with her name. Note that it is acceptable to use @scalar{$username} inside of the string to be printed, and the contents of that scalar are included.

This ends our discussion of our small Perl program. Now that you have some idea of what Perl programs look like, we can begin to look at Perl, its data types, and its constructs in detail.

Expressions, Statements, and Side-Effects

Before we begin introduce more Perl code examples, we want to explain the ideas of an expression and a statement, and how each looks in Perl.

Any valid "chunk" of Perl code can be considered an expression. That expression always evaluates to some value. Sometimes, the value to which expression evaluates is of interest to us, and sometimes it is not. However, we always must be aware that each expression has some "value" that is the evaluation of that expression.

Zero or more expressions to make a statement in Perl. Statements in Perl end with a semi-colon. For example, in the Perl code we saw before, we turned the expression, chomp($userName), into a statement, chomp($userName); by adding a ; to the end. If it helps, you can think about the ;s as separating sets of expressions that you want Perl to evaluate and execute in order.

Given that every expression, even when combined into statements, evaluate to some value, you might be tempted to ask: What does the expression chomp($userName) evaluate to? It turns out that expression evaluates to the total number of characters removed from the end of the variable $userName. This is actually one of those cases where we are not particularly interested in the evaluation result of the code. In this case, we were instead interested in what is called the side-effect of the expression.

The side-effect of an expression is some change that occurs as a result of that expression's evaluation. Often, a side-effect causes some change in the state of the running program, such as changing the value of a variable. In the expression chomp($userName), the side-effect is that any newline characters are removed from the end of the variable, @scalar{$username}.

Let's now consider a slightly more complex statement, and look for the the expressions and side-effect. Consider the statement, $username = <STDIN>; from our first program. In this case, we used the expression, <STDIN> as part of a larger expression, namely $username = <STDIN>. The expression, <STDIN> evaluated to a scalar value, namely a string that represented a line from the standard input. It was of particular interest to us the value to which <STDIN> evaluated, because we wanted to save that value in the variable, @scalar{$username}.

To cause that assignment to take place, we used the larger expression, $username = <STDIN>. The side-effect of that larger expression is that @scalar{$username} contains the value that <STDIN> evaluated to. That side-effect is what we wanted in this case, and we ignore the value to which $username = <STDIN> evaluates. (It turns out that it evaluates to the value contained in $username after the assignment took place.)

The concepts of statements, expressions and side-effects will become more clear as we continue. When appropriate, we'll point out various expression and discuss what they evaluate to, and indicate what side-effects are of interest to us.

Go to the first, previous, next, last section, table of contents.