Secure Email, Web and Form Solutions     +1 800.441.6612
LuxSciLuxSci
Secure Email,
Web and Form Solutions
Call: 800-441-6612
Int'l: +1 814-870-9250
sales@luxsci.com
support@luxsci.com

Introduction to Internet Programming with Perl and HTML: Part 3 – Introduction to Perl

Share Post:
More...
This article is Part 3 of our series on Introduction to Internet Programming series. See the Introduction and Part 1, Introduction to HTML. The Introduction to Perl covers the basics of Perl, including how to write and debug simple scripts.. Perl is a computer programming language that is very good at manipulating strings, doing pattern matches, and pretty much just about everything else! It is a relatively slow language compared to compiled languages like C, however it very easy to get programs up and running very quickly in Perl. Perl stands for "Practical Extraction and Reporting Language". The why of this is that it was originally designed for analyzing large text files and reporting on the results. Since then everything you could want in a programming language, many things you don't want or need, and the kitchen sink have also been added to Perl. In this and the following lessons, we will talk about the basics of using Perl and cover al lot of the common uses. We will not cover advanced topics like references, object-oriented programming, sockets, threads, etc. We will cover variables, files, basic syntax, subroutines and functions, CGI extensions and some other basic functions. After this course, you should have sufficient fluency in Perl to write basic programs for making interactive web sites and a good springboard for learning more Perl. How do you RUN a Perl Program? Just like in HTML, you write your Perl program using a text editor and save it to a text file. The file name should (but doesn't have to) end in .pl or .prl so that it is clear that this is a Perl program. Then, how you run it depends on if you are using Windows or UNIX. In UNIX, you must make sure that the program is executable. I.e. you may need to type something like "chmod u+x my_program.pl" to make your my_program.pl executable. Then, to run it, just type your script name at the command line and hit [Enter]. In Windows, if you have Perl installed, you can either 1. double click on your file, or 2. open a command prompt window, change directory to where you saved your Perl program, and then type perl my_program.pl to run it (typing this will also work in UNIX). On any operating system, there is a quick way to see if your program has any obvious errors before you even run it. At your command prompt, type "perl -cw my_program.pl". The -cw tells Perl to compile your program and tell you any errors or warnings that it can think of, without actually executing your program. If it doesn't say "Ok", then there are problems you need to fix and messages that should help you detect the problem.

Scalar Variables

Consider the following example...
Example 3.2.1: Hello World
#!/usr/bin/perl

# My first program!

print "Hello World!";
print "\n";
All Perl programs (that will run in UNIX or Linux) must have as their first line "#!/usr/bin/perl". This is the location on the computer where the Perl interpreter in located (the program that reads YOUR program and executes it). The location of Perl on your computer may differ from this, You can usually type "whereis perl" at the UNIX command line to find our where Perl is on your computer. Put the location you find after the "#!" symbols as the first line of your program. On lines other than the first line, the "#" symbol means "begin a comment". Everything from this symbol to the end of the line is ignored by Perl (just like everything between "<!-- ... -->" demarks a comment in HTML). Use comments liberally when programming Perl -- this is a requirement! It helps you and anyone reading your program understand what it is supposed to be doing. The next line is the first "statement" in our program, a print statement. Every statement should end in a semi-colon (";"). The print statement displays its parameters (everything after the print) to the user. In this case, everything between the double quotes is displayed to the user. For most cases, you should use double quotes around the text that you want to display to the user. The last line is also a print statement, but it prints something special, the \n "character". In Perl, this means "newline" (like <br> in HTML). It is usually nice to put such newlines after each line you print, or else all our lines will run together and it won't look nice.
Example 3.2.2: Print Your Name
#!/usr/bin/perl

   # This program will print my name!

$myname = "Erik Kangas";
print $myname, "\n";
This program introduces a new concept, that of the variable. Here we have a variable named myname. We know it is a variable because it is prefixed with the dollar sign, ("$"). We can store a value in a variable by using the equals sign. In this case we store the name Erik Kangas in the variable. The name is a piece of text. Whenever you use text in Perl, you must enclose it in quotation marks, in this case, we use double quotes. You can print multiple things all at once, if you separate them with a comma (think of this as printing a list of things separated by commas). We see that when we use $myname in the print statement, the value stored in that variable is retrieved and printed. So, it is EASY to store and retrieve values with variables, use "=" to store, and use the variable in place of text (or a number as we will see) and its value will be retrieved. Perl is also like HTML in that Perl doesn't care much how many spaces or line feeds you use. As long as it can be logically deduced what you mean, you can use as few or as many spaces as you want. If you make a mistake, Perl will tell you when you try to run your program. The exception to this is inside the quotation marks -- every space and line feed there is REAL, you are quoting exactly the text that you want to use. Inside quotation marks, 2 spaces means 2 spaces, period.
Example 3.2.3: Number Variables
#!/usr/bin/perl

   # Using numbers in variables

$x = 33.578;
$y = "5";

print "$x, $y\n";    ## Prints "33.578, 5\n"
We can also store numbers in variables. With numbers, the quotation marks are optional. When printing variables, you can put the variable inside the double quotes and it will still retrieve and store its value! As you can see, this simplifies your print statements. (Technically, this is called variable interpolation).

Let's Do Math!

Perl, like any programming language, has a great facility for allowing you to perform mathematics! Mathematics is performed using "operators". There are a lot of operators, none of them are the following....
Exponentiation: Binary "**" is the exponentiation operator. It binds even more tightly than unary minus, so -2**4 is -(2**4), not (-2)**4, i.e. 2 to the power 4 (the negative of it all). Unary Minus: The operator "-" returns -1 times the number it is operating on. Multiplication: Binary "*" multiplies 2 numbers. Division: Binary "/" divides 2 numbers. Modulus: Binary "%" computes the modulus of two numbers. Given integer operands A and B: If B is positive, then A % B is A minus the largest multiple of B that is not greater than A. If B is negative, then A % B is A minus the smallest multiple of B that is not less than A (i.e. the result will be less than or equal to zero). Addition: Binary "+" adds 2 numbers. Subtraction: Binary "-" subtracts 2 numbers. Concatentaion: Binary "." concatenates 2 strings (returns one appended to the end of the other). This is not really "math", but this is a good time to bring this one up...
These operations follow the same order of operations you are used to from algebra. If you want to make sure that you perform a low priority action (such as addition) before a high priority action (such as multiplication), you must use parenthesis. The order of operations is, from highest priority, to lowest:
Example 3.3.1: Order of Operations
**             Exponentiation
-              Negation
* / %          Multiplication, Division, Modulus
+ - .          Addition, Subtraction, Concatenation
=              Assignment
These operators can operate on explicit numbers or the numbers stored in variables. For example:
Example 3.3.2: A Little Physics Please...
#!/usr/bin/perl

# Calculate the vertical position of a projectile
# launched from a position $y0 with a velocity $v0
# on Earth where we know the gravity, assuming that the projectile
# is fired from ground level ($y0=0) and is airborne for a time $t.

$g  = 9.8;       ## Gravitational Accel. 9.8 m/s**2

$y0 = 0.0;       ## Launch from Y = 0
$v0 = 10.0;      ## 10 meters / second in the Y direction
$t  = 5.0;       ## 5 seconds in the air.

$y1 = $y0 + $v0 * $t - 0.5 * $g * $t ** 2;

print "The projectile traveled ",
      ($y1 - $y0), " meters\n";
Here we see the use of comments and the need to initialize all of your variables before you try to use them (if you fail to give a variable a value, it will behave as if it had a value of zero in your math). We also see how we can use many of the operators to perform a mathematical calculation, store the result in $x1 and print the result. Also, note that you can perform calculation in the middle of trying to print! Perl performs all calculations before passing the list of things to print or any other function you may be using.
Example 3.3.3: More Math
#!/usr/bin/perl

#
# This is an example of performing more
# complex mathematical calculations...
#

$a = 5;
$b = 25;

$c = - ($b - $a) * ($b + $a);      # (25 - 5)(25 + 5) => 600
$c = $c + 1 + $a**( ($b-1)/12 );   # 600 + 1 + 5 ** ( (25-1)/12 )

print "The result is '$c'\n";

# String concatenation...

$string = "ABCDEFG";
$string2 = $string1 . "-" . $string2;
print "$string2\n";               ## print "ABCDEFG-ABCDEFG\n";
Here we show the necessity of the use of parenthesis if you need to make sure some calculations happen before others. You also see that you can use the same variable on both sides of the equals sign, i.e. $x = $x + 1 does what you would expect, it results in $x becoming larger by 1. The last part of the example shows how we can use the string concatenation operator to make bind strings of text out of little ones.

User Input

The examples above are great, but they suffer from the central problem that you are "hard-coding" the parameters inside the program itself - to calculate something different, you need to change the program. It would be much better if we could ask the user for the parameters, so the programs would be much more generally useful! That's what we do here....
Example 3.4.1: A Little More Physics Please...
#!/usr/bin/perl

# We will ask the user for the parameters, so we better
# TELL the user what we are doing and what he needs to type,
# that's only fair!

print "The program calculates the vertical position of a projectile\n";
print "That has an initial Y velocity v0, and which is in the air\n";
print "for t seconds.  Please supply values for these parameters:\n";

print "Enter v0: ";      ## Note, no \n here....
$v0 = <STDIN>;          ## Read a LINE of input from the user
chomp($v0);             ## Delete the \n at the end of the line.

print "Enter t: ";        ## Note, no \n here....
$t = <STDIN>;             ## Read a LINE of input from the user
chomp($t);                ## Delete the \n at the end of the line.

$g  = 9.8;        ## Gravitational Accel. 9.8 m/s**2

$dy = $v0 * $t - 0.5 * $g * $t ** 2;

print "The projectile is a position y=$dy\n";
Wow! Now we have a real program! When we run this it will be truly interactive and useful! There are two new concepts here. Assigning a variable from the symbol "<STDIN>" causes Perl to read a line of input from the user. The entire line, including the "Enter" key (a \n) is then stored in your variable. So, if the user types in "55.3[Enter]", your string will be "55.3\n". To eliminate the unneeded \n from the input we use the function chomp, which eats all \n it finds in your string (note that chomp changes your string in place and doesn't return your string, so you don't want "$x = chmop($x)" -- that would not do the right thing. Stick with "chomp($x)".). Note: STDIN must be in all caps. Use of input in this way is very good for writing Perl programs that you run from the command line, but will bot be useful later when we start getting our input from the Internet.

Details, Details

Here we talk about details and things to watch our for. Debugging: At this point, finding errors in your programs consists of just running the program and seeing if it works. Here are some tips:
  • If your program is running and you want to stop it, press Control-C, i.e. press both of these keys at the same time.
  • If you are getting errors, first make sure that you have semi-colons, ";", at the end of all the lines! Then make sure that if you use quotation marks, that you have quotes on BOTH sides of your string.
  • If Perl is complaining about some particular line, there is also a good chance that the error is actual happening on the previous line.
  • Everything in Perl is case sensitive, unlike in HTML. So, $MyVariable is completely DIFFERENT from $myvariable. Same goes for the functions, there is no function Print, only print.
  • Variable names must begin with a letter and can contain only letters, numbers, and the underscore character ("_"). They can be of almost any length. The names ARE case sensitive. You cannot have any space between the dollar sign prefix to the variable name and the variable name itself. I.e. "$ x" is incorrect.
Quotation marks: So far, we have just used double quotes for all text. You can also use single quotes, i.e. "$x = 'Super Duper!'". The difference is that if you use single quotes, the contents of any variables inside the quotes will not be retrieved, and "\n" will not become a linefeed. Instead, these things will be used as-is. I.e. "print '$x';" will print the two characters dollar sign and x, and not the contents of $x. If you ARE using double quotes and you want to print a dollar sign or a backslash ("\") or other special character, you must prefix the special character with a backslash. So, "\$x" is the same as '$x'. This allows you to mix substitutions and explicit stuff with "The price of $item is \$5.50\n".

Your Homework

Your homework consists of the writing of 2 simple Perl programs:
  1. Write a MadLib with at least 8 blanks to fill in. I.e. Think of a paragraph of text, remove 8 or more of the words (i.e. a noun, a verb, someone's name, etc.). Prompt the user for each of these 8 words, telling him what it is for ("Give me an action verb ", "Give me the name of a person ", etc.). Store these answers in variables, then print out your paragraph to the user with his answers substituted for the words you removed. The result can be very funny, since the user shouldn't know what the paragraph will say ahead of time! For an example of this, see Julius Caesar Madlib -- yours should be completely different.
  2. Write a program the calculates the length of the hypotenuse of a right triangle. You should ask the user for the lengths of the legs of the triangle before you make the calculation. You will find the function sqrt useful. This returns the square root of its argument, i.e. " $r = sqrt($x); " assigns the square root of $x to $r, and "print sqrt(9);" prints 3.

Similar Posts:

Share:
More...

Leave a Comment

You must be logged in to post a comment.

Security Certifications TRUSTe EU Safe Harbor Thawte Extended Validation SSL Certificate McAfee Secure Authorize.net Merchant