[Courses] [Perl] Part 4.5

Dan Richter daniel.richter at wimba.com
Fri Jul 25 12:22:37 EST 2003

LinuxChix Perl Course Part 4.5: Review

Since this course has encountered a three-month interuption, I thought we
should start back up with a refresher lesson. Refer back to the original
lessons if you get lost, or ask for help from the list.

Note that there's a little new material at the end.



1) Getting Started
2) Scalar Data
3) User Input
4) Control structures
5) New Stuff
6) Exercises


1) Getting Started       Complete Lesson:

Your Perl files should start with a "shebang" line. It should look something
like this:

   #!/usr/bin/perl -w

The /usr/bin/perl is the location of the Perl interpreter (you should set it
to wherever Perl is on your system). The "-w" switch means "warn me if I do
something that looks like a mistake."

Although this technically comes from lesson two, I thought I would mention
here that the second line of your Perl programs should always be "use
strict;". This has a function similar to the "-w" switch, but "use strict;"
and "-w" cover different mistakes, so you should use them both.

Here is a Hello World program:

   #!/usr/bin/perl -w
   use strict;

   print "Hello, world!\n";

The "\n" at the end causes a newline to be printed, because "print" doesn't
automatically output a newline.


2) Scalar Data       Complete Lesson:

Now we're going to look at "scalar" variables. Scalar is the simplest type of
variable: it always refers to a single "thing", such as a number or a piece of
text (which can be multiple words). We'll see a more complicated type of
variable when we deal with arrays.

Scalar variables are preceded by a dollar sign, like this:

   my $foo;

The word "my" declares the variable. In other words, it says, "make this
variable magically come into existance". You should declare a variable before
using it. You can declare a variable and give it a value at the same time,
like this:

   my $foo = 'some text';      # Set $foo to be the words "some text".

Here we use strings, but we can also use numbers:

   my $minutes = 12;
   my $seconds = $minutes * 60;
   print $seconds;            # Output is 720.

Perl includes several operators on strings (text), including "."
(concatenation) and "x" (multiplication):

   my $text = 'abc';
   $text = $text . 'xyz';   # Now $text = 'abcxyz'
   my $longtext = $text x 3;
   # Now $longtext = 'abcxyzabcxyzabcxyz'

Don't use a plus sign to concatenate strings! The plus sign means numerical
addition only!

Single and double quotes have different meanings. Inside of double quotes,
variables (e.g., beginning with "$") and special characters (beginning with
"\") are interpreted (replaced with appropriate values). Inside of single
quotes, variables and "\" are not interpolated. (Actually, "\" is interpolated
ONLY if followed by a single quote or another "\".)

   my $value = 'fish';
   my $foo = "Eat $value\n";   # Result is: Eat fish [newline]
   my $bar = 'Eat $value\n';   # Result is: Eat $value\n


3) User Input       Complete Lesson:

The "diamond operator", or "<>", is placed around a filehandle to read a line
from it. You can define your own filehandles, but the special filehandle STDIN
is always defined for you:

   #!/usr/bin/perl -w
   use strict;

   my $line = <STDIN>;
   print "You wrote: [$line]\n";

Note that the input includes the newline character at the end of the line. Use
"chomp" to remove it:

   #!/usr/bin/perl -w
   use strict;

   my $line = <STDIN>;
   print "You wrote: [$line]\n";

You can't write "$line = chomp(<STDIN>)" because "chomp" alters the value
passed in rather than returning the changed input. If you want to be really
tricky, do this:

   chomp(my $input = <STDIN>);

The record separator ("$/") controls how input is broken into readable pieces,
and "chomp" always removes $/ from the end of the line. You can set it as

   $/ = ",";

Now "<STDIN>" will read text up to (and including) the first comma, and
"chomp" will cut that comma off the end of the input.


4) Control Structures       Complete Lesson:

Like pretty much every other (imperitive) programming language, Perl uses the
"if" control structure.

   if ( <condition> ) {
     # Do something here.


   if ( <condition> ) {
     # Do something here.
   else {
     # Do something else here.

Perl also has the innovative "unless" keyword. "unless ( <condition> )" has
the same meaning as "if ( not <condition> )".

   unless ( $number == 5 ) {
     print "The number is not 5.\n";

You can also add an "else" after "unless", but only a truly twisted soul would
do that!

The "while" keyword causes commands to be executed as long as a condition is

   #!/usr/bin/perl -w
   use strict;

   # Count to ten.
   my $x = 1;
   while ( $x <= 10 ) {
     print "x = $x\n";
     $x = $x + 1;

In contrast to "while", "until" loops if the condition is false:

   #!/usr/bin/perl -w
   use strict;

   # Count to ten (again).
   my $x = 1;
   until ( $x > 10 ) {
     print "x = $x\n";
     $x = $x + 1;

Both "if" and "unless" can be written after the statement, too:

   print "Your account is overdrawn.\n" if $money < 0;

The same is true of "while" and "until".

All of these keywords ("if", "unless", "while" and "until") require braces and
parentheses unless used after the statement.


5) New Stuff

I'd like to point out a few things that haven't been mentioned out before.

Perl allows you to make the same type of "if-assignment" as C:

   if ( $x = 10 ) { ... }    # Uh oh...

Do you see the error? It should be "==" instead of "=":

   if ( $x == 10 ) { ... }   # Much better.

If you have faithfully turned on warnings, Perl will warn you of that one, but
not this one:

   if ( $x = $y ) { ... }    # Possible mistake, but no warning.

Perl doesn't warn you because assignment may in fact be what you want,
especially in a loop:

   #!/usr/bin/perl -w
   use strict;

   my $line;
   while ( defined($line = <STDIN>) ) {
     print "$line\n";

The while loop terminates when there's no more input.

(If you execute this program, enter a few lines and then hit Ctrl+D [hold down
Control and hit D] to indicate that you don't want to input anymore. There's a
chance that Perl will wait for you to hit Ctrl+D before it begins repeating
what you input.)

One other thing that wasn't pointed out before that I think worthy of noting:
even though numbers and text can be stored in the same type of variable, they
use different comparison operators. Operators like "<", ">" and "==" are for
numbers. For text, use:
   eq (equal)
   ne (not equal)
   lt (less than)
   le (less than or equal to)
   gt (greater than)
   ge (greater than or equal to)

For example:

   my $x = 'Larry Wall';
   my $y = 'Alex Nobrain';
   if ( $x gt $y ) {
     print "$x is greater than than $y\n";

If you're wondering why this is, consider this comparison:

   my $a = '   25  ';
   my $b = 25;
   if ( $a == $b ) { ... }

Perl is happy to strip the white space off of $a and treat it as a number, but
maybe you intended to treat $b as a string instead. So you have to explicitly
specify whether you want a string comparison or a numerical comparison.


6) Exercise

This exercise is taken from previous material, but made slightly more

Write a program that reads numbers from the keyboard (one number per line)
until there's no more to read, then outputs the average of all those numbers.

Here are some things to remember:
a) Use "while ( defined($line = <STDIN>) )" to loop until there's no more
b) When entering information, hit Ctrl+D to signal the end of the data.
c) Don't forget "use strict;" and "-w"!

More information about the Courses mailing list