Perl Primer

You may run all of these programs from your own account by changing directory to ~downeyt/public_html/cop3832/perl
Alternatively, you may execute them via the web from this link: Run Examples.

#!
Every Perl program must have a comment on the first line that indicates the location of the Perl interpreter. On solix, mongoose and weasel the comment should be
#!/usr/local/bin/perl
Hello World program
Use the -w switch to have perl warn you when you are doing sloppy things
#!/usr/local/bin/perl -w
Warning program
Add the -T switch to enable taint checking, which forces you to validate input before executing it on the server
#!/usr/local/bin/perl -T
Tainted Environment program
Tainted Input program
Use the package strict to prevent you from doing sloppy things. Most warnings now become errors
#!/usr/local/bin/perl
use strict;
Strict program
Combine all ot them to help catch bugs in your code
#!/usr/local/bin/perl -wT 
use strict;
$variables
The $ in front of a variable indicates that the value is a scalar. A scalar is a single value, as opposed to an array or a structure. Check out some examples of initializing variables.
@variables
The @ in front of a variable indicates that the value represents an array. An array contains one or more scalar values. Check out some examples of initializing variables.
%variables
The % in front of a variable indicates that the value represents an associative array, called a hash array in Perl. An associative array is an array that is indexed by strings instead of numbers. Check out some examples of initializing variables.
Decalaring variables with my and local
It is a good habit to declare all variables before you use them. You can force the interpreter to check this by including the command
use strict;
at the start of the program. There are two ways to declare a variable: my and local. The preferred method for this course is my. A variable declared with my bahaves like local variables in other high level languages (like var variables in JavaScript). The only exception for this course will be file handles: use local to declare them. A variable declared with local defines a global variable for the scope in which it is created. If there is already a global variable with the same name, then the new value will be used, but when the new variable goes out of scope, the global variable will revert to its original value. Check this example for the difference between my and local.
Standard input
STDIN is a file handle that is predefined. Use it to read an entire line from the user into a scalar variable
my $line;
$line = <STDIN>;

chomp ($line);
The chomp function removes the last character from the line if it is a newline character. <STDIN> always returns the newline.
Standard output
Display information using the print function
print "This is some output\n";
print "This ", "is ", "output ","too\n"; 
Control structures
Control structures in Perl are similar to those in JavaScript: for and while are exactly the same; if and foreach are similar.
The if...else construct is different in Perl. Perl requires the { }, even if there is only one statement in the if. To avoid a lot of unnecessary { }, the else { if (...) ... } can be combined as elsif (...) {...}
With elsif Without elsif
if ($x == 1) {
    print "one\n";
} elsif ($x == 2) {
    print "two\n";
} elsif ($x == 3) {
    print "three\n";
} else {
    print "other\n";
}
if ($x == 1) {
    print "one\n";
} else {
    if ($x == 2) {
        print "two\n";
    } else {
        if ($x == 3) {
            print "three\n";
        } else {
            print "other\n";
        }

    }
}


foreach loops are similar to for..in loops in JavaScript but use ( ) instead of in. Also in Perl, the values of the array are returned, not the indexes.
JavaScript Perl Perl mimicking JavaScript
for (pos in list) {
  total += list[pos];
}
for $val (@list) {
  $total += $val;
}
for $pos (0..@list) {
  $total += $list[$val];
}

Declaring functions
Functions are similar to those in Javascript, except the word sub is used instead of function. Also, the definition of the parameter list is different.
JavaScript Perl
function fun(a, b, c) {
 ...
}
sub fun {
  my (a, b, c) = @_;
  ...
}

Functions are called the same way in JavaScript and in Perl.

Passing arrays by reference
To pass an array by reference, include a \ before the name in the parameter list of the call:
fun (\@list);
This will send a reference (a pointer) to the array to the subroutine. In the function, copy the reference to a scalar variable:
sub fun {
    my ($ref_list) = @_;

Then, de-reference the pointer to access the list. Think of {$ref_list}as the name of the parameter that was sent to the function, and prepend the type of variable that you are accessing in the function ($, @, or %).
@{$ref_list} = (10,20,30);
or, access individual elements
${$ref_list}[2] = 40;
You can also access the size of the array. When an array is used in a scalar context (single-value context), then the number of element in the array is returned.
my $length = @{$ref_list};
Returning more than one value from a function
It is possible to return more than one value from a function: just return a list.
sub fun {
    ...
    return ("hello", 1);
}

This function returns the list containing the string "hello" and the number 1. Retrieve them in the main program into a list:
($string, $number) = fun();
Opening files
It is possible to open a file using Perl
Opening for reading Opening for writing Opening for appending
local *FILE;
my $line;
open (FILE, "in.txt");
$line = <FILE>;
close FILE;
local *FILE;
open (FILE, ">out.txt");
print FILE "Hello";
close FILE;
local *FILE;
open (FILE, ">>out.txt");
print FILE " World\n";
close FILE;
Testing if a file was opened
You can use the defined function to determine if a file has been opened:
if (defined *FILE) {
...
}
", ', and `
There are three types of quoting in Perl that is similar to the quoting for Unix shell scripts.  See an example.
Regular expressions
Regular expressions are used in many ways. See some examples for creating regular expressions.

It is possible to change the / charcter to any other character, in case you need to match the /. Just use any other character in place of the /.

Relational operators for strings and numbers
There are different operators for strings and numbers. If you use the wrong operators, then your variables will be treated as the wrong type.
String Operators Numeric Operators
eq
ne
gt
ge
lt
le
. (concatenation)
==
!=
>
>=
<
<=
+ (addition)
equal
not equal
greater than
greater than or equal
less than
less than or equal