Node:A First Perl Program, Next:, Previous:Getting Started, Up:Getting Started



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.

     #!/usr/bin/perl
     
     use strict;                        # important pragma
     use warnings;                      # another important pragma
     print "What is your username?  ";  # print out the question
     my $username;                      # "declare" the variable
     $username = <STDIN>;               # ask for the username
     chomp($username);                  # remove "new line"
     print "Hello, $username.\n";       # print out the greeting
     
     # 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 -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 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 strict mode (set by the use strict pragma), all variables must be declared. In this case, Perl's my keyword is used to declare the variable $username. A variable like $username that starts with a $ is said to be a scalar variable. For more information on scalar variables, see 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, $username, that we declared in the line before it. Since $username is on the left hand side of the =, that indicates $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. 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 $username variable. Since we got the contents of $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 $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, chomp, removes any newline characters that are on the end of a variable. So, after the chomp operation, the variable $username

The final statement is another print statement. It uses the value of the $username variable to greet the user with her name. Note that it is acceptable to use $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.