

Now that we've covered HTML, UNIX, and the command line, it's time to actually start programming! Some content in this lesson is adapted from Learning Perl, by Randal L. Schwartz, which I highly recommend if you want to continue learning Perl beyond these classes.
It's worth taking a moment to discuss the differences between compiled programming languages and scripting languages 1. Compiled languages, such as C and C++, are converted by a compiler into your computer's native assembly language for execution on its CPU. This is good because it allows direct execution on your CPU, tending to result in fast code. However, programs written in compiled languages must be re-compiled every time they are edited, which is slow.
On the other hand, scripting languages are run inside of an interpreter that acts as an intermediary, reading the code file, interpreting the code, and issuing commands to the CPU. Because the code must be interpreted (basically, dynamically compiled at run-time), scripting languages tend to be slower than compiled languages. However, the gain for this speed loss is significant. Interpreted languages can do things that it are very difficult to do in compiled languages. Interpreted languages don't need to be compiled, come with very advanced features built-in, and can do weird things, like being self-referential. Many modern programming languages blur the distinction between compiled and interpreted. Java, Python, and to some extent Perl, are all compiled to bytecode before being executed.
Lets start programming!
Computer programming borrows much from mathematics. Just like in math, we have variables ($x, %y, $myVar), functions (sin(), cos(), myFunc(), sort()), and operators (*, +, /, %, .). Additionally, most programming languages adopt a similar sequence of operations as mathematics, so that 2 * 3 + 5 = 11 not 16.
A computer program is an algorithm--a logical sequence of operations or tasks to get something done. When we program, we carefully specify every step of a process. Remember, a computer only does what you tell it to. If it does something wrong, then you (or someone else) failed to specify exactly what it should be doing.
Perl (Practical Extraction and Report Language) started in 1987 and has since become extremely popular as a system administrator tool and an online CGI programming language. (CGI will be covered in a future lesson.) For a good overview of Perl's features, see perl.org. Perl is flexible and powerful, but sometimes cryptic. The tagline of Perl is "There's More Than One Way to Do It." However, that doesn't mean that all possible solutions are good solutions.
#!/usr/bin/perl print "Hello, world!\n";
Output: Hello, world!
#!/usr/bin/perl $j = "Hello, "; $k = "world!"; print $j . $k . "\n";
Output: Hello, world!
$j = "Hello, world!";
$j = 42;
The . operator concatenates (joins) strings together. For example:
$j = "Hello, " . "world!";
#!/usr/bin/perl # This program asks for your name, and then greets you! print "Hello! What is your name? "; $name = <STDIN>; chomp($name); print "Well, hello $name! Nice to meet you!\n";
Output:
Hello! What is your name? Andrew Well, hello Andrew! Nice to meet you!
#!/usr/bin/perl $j = 42; $k = 10.56; $c = $j/$k + 5; $d = ($c - 10)*6 - 1;
#!/usr/bin/perl $j = "I"; $k = " stutter"; $c = $j . ($k x 5) . "!\n"; print $c;
Output: I stutter stutter stutter stutter stutter!
Lets start with a pretty complicated example that illustrates the use of conditionals and loops. Conditionals let us execute some Perl statements 2 conditionally on the results of other statements. We will introduce if, while, and for here. Another loop statement is the foreach statement, and that will be introduced in a little while.
#!/usr/bin/perl -w
print "Enter your name: ";
$name = <STDIN>;
chomp($name);
print "Hello $name! How many times should I greet you? ";
$greet = <STDIN>;
chomp($greet);
if ($greet > 0) {
$j = 0;
while($j < $greet) {
print "Hello $name! ($j)\n";
$j++;
}
} else {
print "Okay, I guess I won't greet you then.\n";
}
print "All done!\n";
Take a look at this pseudocode 3:
if (logical expression) {
do something
} else {
do something else
}
The if statement executes the code in the block inside the {} characters. The else is an alternative case. You can skip it if you want. You can also have multiple cases. More pseudocode:
if (logical expression) {
do something
} elsif (another logical expression) {
do something else
} elsif (yet another logical expression) {
do something for this third case
} else {
otherwise, do this
}
$j = 10;
while($j > 0) {
$j = $j - 1; # Or I could use $j--; or $j -= 1;
print "Counting down. Now I'm at $j\n";
}
Output:
Counting down. Now I'm at 9 Counting down. Now I'm at 8 Counting down. Now I'm at 7 Counting down. Now I'm at 6 Counting down. Now I'm at 5 Counting down. Now I'm at 4 Counting down. Now I'm at 3 Counting down. Now I'm at 2 Counting down. Now I'm at 1 Counting down. Now I'm at 0
Notice that the while loop executes while a conditional is true. (Also, know that 0 is equivalent to false, and any other number or string is true. Therefore, while (1) {} is an infinite loop, as is while ("andrew") {}, but while (0) {} never even runs the while block because it's false.)
for($j = 0; $j < 10; $j++) {
print "Now counting up. Now I'm at $j\n";
}
# Or another example like the while loop above
for($j = 10; $j > 0; $j--) {
print "Counting down. Now I'm at $j\n";
}
Output:
Now counting up. Now I'm at 0 Now counting up. Now I'm at 1 ... Now counting up. Now I'm at 8 Now counting up. Now I'm at 9 Counting down. Now I'm at 10 Counting down. Now I'm at 9 ... Counting down. Now I'm at 2 Counting down. Now I'm at 1
As you can see, for loops can be used as concise while loops. The first part of the for statement typically assigns a starting value to a variable. The second part (after the first semicolon) is the conditional -- the loop will continue until this conditional fails. The third part usually increments or decrements the loop variable. In the first example above, the variable is incremented with the ++ operator, identical to $j = $j + 1. In the second example, the variable is decremented with the -- operator, identical to $j = $j - 1. The ++ and -- operators are basically useful shorthand 4.
As you probably gathered from above, Perl has a number of useful comparison operators. Here are a few for numbers:
if ($j < $k) {
...
$j = 5;
$k = $j;
if ($j == $k) { # This statement is always true.
...
while ($stop != 1) {
if (not ($j == $k)) {
...
The above Boolean 5 operators work only for numbers. If you use them on strings, Perl will convert the strings to numbers and then apply the operations. Here are some string comparison operators:
if ($name eq "Andrew") {
...
Finally, you should know the Boolean Logic operators &&, ||, and !. We saw ! (NOT) before, but lets look at the other two: AND and OR.
# The following will be True if $j > 5 or $j < 1
if ($j > 5 || $j < 1) {
...
# The following will be True if $name ne "Andrew" and $count < 10
if ($name ne "Andrew" && $count < 10) {
...
Functions in Perl are like functions in math. (Actually, everything we have been doing is really a function or an operator, which is pretty much a function.)
#!/usr/bin/perl
print power(5,2); # Prints 25
$j = power(2,2); # $j is now 4
# power(number,power) returns
# number raised to power.
sub power {
local($i,$t);
local($n, $p) = @_;
$t = $n;
for($i = 1; $i < $p; $i++) {
$t = $t * $n;
}
return $t;
}
Arrays are lists of values. It's best to learn by example, I think, so here we go:
@array = ("leeds", "barclay", "jones", "lunt", "hca");
print $array[0] . "\n"; #This prints 'leeds'
print $array[2] . "\n"; #This prints 'jones'
$array[1] = "comfort"; #Now the list is: leeds, comfort, jones, lunt, hca
print "Everything I know:\n";
foreach $dorm (@array) {
print " $dorm\n";
}
leeds jones Everything I know: leeds comfort jones lunt hca
for ($j = 0; $j < 5; $j++) {
print $array[$j] . "\n";
}
@array = (5, 2, 27, &power(2,5), "andrew"); $array[3] = $array[0] + $array[1]; push @array, "another element"; print pop(@array); #will print "another element"
Hashes are sets of key/value pairs. Take the following example:
%names = ('matt'=>'nocifore', 'andrew'=>'cantino', 1=>'one');
print "Looking up 'matt': " . $names{'matt'} . "\n";
$names{'nick'} = "travers"; #Added a new name to the hash
$names{'ali'} = "rosenberg"; #Added a new name to the hash
print "Everything I know:\n";
foreach $item (keys(%names)) {
print " $item: $names{$item}\n";
}
print "Now in alphabetical order:\n";
foreach $item (sort(keys(%names))) {
print " $item: $names{$item}\n";
}
Looking up 'matt': nocifore Everything I know: ali: rosenberg 1: one andrew: cantino matt: nocifore nick: travers Now in alphabetical order: 1: one ali: rosenberg andrew: cantino matt: nocifore nick: travers
We will cover more Perl in the next few weeks, but here is a list of useful Perl resources:
Use what we learned from the last lesson to make a new file in your UNIX shell called example.pl.
ssh acantino@acantino.people.haverford.edu acantino@acantino.people.haverford.edu's password: -jailshell-2.05b$ pico example.pl
Type or paste in one of the example programs from this lesson, then save it. Then, run it by entering
perl example.pl
Once you get it working, edit the file again with pico (pico example.pl again) and play with making a few changes in the Perl code. By far the best way to learn to code is by doing it!
Try some or all of these ideas for your own programs. To learn more, read the Perl documentation (or use perldoc on the shell -- man perldoc) and Rex Swain's HTMLified Perl 5 Reference Guide. Also, feel free to contact me.
Program ideas:
Next time we do files and online CGI!
 
[1] - It seems that this distinction isn't made too much anymore. As the processing power of computers increases, interpreted languages, with their ease-of-use and flexibility, are becoming more and more appealing as general programming solutions.
 
[2] - http://www.unix.org.ua/orelly/perl/perlnut/ch04_03.htm
 
[3] - 'Pseudocode is a short hand way of describing a computer program. Rather than use the specific syntax of a computer language, more general wording is used.' -- http://nicklas.byriel-pedersen.dk/Glossary/Glossary.htm
 
[4] - They're also in-place, and order matters, so $j-- is different than --$j. Also, $j++ is the same as $j+=1 .
 
[5] - Boolean refers to Boolean Logic, named after George Boole. Boolean Logic is true/false or two-valued logic, and is the logic that computers use.
 
[6] - http://www.htmlite.com/perl014a.php
This document was generated using AFT v5.094