Perl Programming
 

 

I. Introduction
        PERL (Practical Extraction and Report Language)  is a general purpose programming language. It can be used for anything that other programming language can be used for. It has been used in every industry imaginable for almost any task you can think of. It's used on the stock market, manufacturing, design, customer support, quality control, system programming, payroll, inventory, and on the Web.

Perl is used in many (more than 20) operating system: Unix, Macintosh, DOS/Windows, VMS, MPE, Web application, because Perl is what's known as a glue language. A glue language is used to bind things together.
Perl can take your database, convert it into a spreadsheet file, and during the processing, fix the data if you want. Convert the word processing documents to HTML for display on the Web.
 

Installing Perl
    Some Unix vendors ship Perl with the operating system. Windows NT comes with Perl as part of the Windows NT Resource Kit. To see whether Perl is properly installed on your Unix system, type the following:
$ perl -v

If you have a Windows PC, to see whether Perl is properly installed, you need to get to  an MS-DOS prompt:
C:\> perl -v

Installing Perl on Windows 95/98/NT: download  the installation file from www.ActiveState.com
Installation Perl on Unix: download the source bundle from www.perl.com, the file named something like stable.tar.gz, then you need to unpack and install it. To do so, enter these commands:

$ gunzip stable.tar.gz
$ tar xf stable.tar
$ sh Configure

Configure starts and asks you a lot of questions. If you don't know the answers to most of them, that's fine; just press Enter.
When that's all done, type this command:

$ make

Building Perl takes quite awhile. Get some coffee. When the build is complete, type two more commands:
$ make test
# make install

The make test command ensures that Perl is 100 percent okay and ready to run. To run make install, you might need to be logged in as root.

II. Your First Program
Open your text editor, and type the following Perl program exactly as shown:

#!/usr/bin/perl
print "Hello, World!\n";

Save it in a file named hello. In MS Windows, open an MS-DOS prompt, you should also change into the directory where you stored the hello program, for example programs directory. To run the program, type:
C:\programs> perl hello

To add a comment line in the program, just put # in the line as a first character. In Unix, usually Perl located in /usr/bin or /usr/sbin directory. The first program's line (#!/usr/bin/perl)  tell to Unix shell that "Its a Perl script!"
To run the hello program in Unix, you should change the hello file permission to 755 (executable mode):

$ chmod 755 hello
# hello

-------------------------------------------------------------------------------------------------

III. Numbers and Strings
Interest Calculator program, it count how much total the deposit on the future,  from your monthly deposit amount with the annual interest and number of months to deposit.

#!/usr/bin/perl -w
# This line contains the path to the interpreter and the -w switch (warning enabled).
print "Monthly deposit amount? ";      # The user is prompted for an amount
$pmt=<STDIN>;                             #Read the monthly deposit amount  from keyboard
chomp $pmt;                                    #The newline character is removed from the end of $pmt

print "Annual Interest rate? (ex. 7% is .07) ";    # The user is prompted for an interest rate
$interest=<STDIN>; chomp $interest;

print "Number of months to deposit? ";            # The user is prompted for an numbers of months
$mons=<STDIN>; chomp $mons;

# Formula requires a monthly interest
$interest/=12;
$total=$pmt * (( 1+ $interest) ** $mons -1 )/ $interest;

print "After $mons months, at $interest monthly you\n";
print "Will have $total.\n";

----------------------------------------------

IV. Controlling the Program's Flow

The if Statement
To control whether statements are executed based on a condition in a Perl program, use an if statement. The syntax  of an if statement is as follows:

if (expression)  BLOCK

When the expression is true, the block of code is run. If the expression is false, the block of code is not run.

A small number guessing game source program:

#!/usr/bin/perl -w
$im_thinking_of = int (rand 10); # Random number from 0 to 9
print "Pick a number:";               # Make a guess by typing a number 0 - 9
$guess=<STDIN>;                      # save the input from keyboard to $guess
chomp $guess;                             # remove the newline code in $guess
print "Random number is $im_thinking_of \n";
# Print the random number, and put the cursor on the new line (\n)

# If your input number bigger than random, print "Your guessed too high"
if ($guess > $im_thinking_of)

{
        print "You guessed too high!\n";
}

# If your input number smaller than random, print "Your guessed too low"
elsif ($guess < $im_thinking_of)      {
        print "You guessed too low!\n";
}

else        {
       print "You got it right!\n";
}
 

------------------------------
Looping with while, example:

#!/usr/bin/perl -w
$counter=0;
while ($counter < 10 ) {
    print "Still counting...$counter\n";
    $counter++;
}
 

------------------
Looping with for
Perl allows blocks and some loop statements (for, while) to be labelled. That is, you can place an identifier in front of the block or statement:

MYBLOCK:        {
}

The preceding block is labelled as MYBLOCK. The last, redo, and next statement can each take a label as an argument.

#!/usr/bin/perl -w
outer: for ($i=0; $i<100; $i++)
        {
        for ($j=0; $j<100; $j++)
                {
                if ($i * $j == 140)
                        {
                        print "The product of $i and $j is 140 \n";
                      last outer;
                        }
                }
        }

Now the last statement can specify which loop it wants to exit-in this case, the outer loop.
 

---------------------------------

V. Arrays

#Lists and arrays

#!/usr/bin/perl -w
@flavors=qw( chocolate vanilla strawberry mint sherbert );
# Array flavors has records: chocolate,vanilla,strawberry,mint,sherbert
for ($index=0; $index<@flavors; $index++)        {
        print "My favorite flavor is $flavors[$index] and...";
        }
        print "many others.\n";

foreach $cone (@flavors)                 # Print the record, one by one
        {
        print "I'd like a cone of $cone \n";
        }

$record=(@flavors);                        # record = the amount of records in array flavors
print "$record records: ", join(' ', sort @flavors);
 

---------------------------------------

#Converting between array and skalars

#!/usr/bin/perl -w
@words=split(/ /, "The quick brown fox");
# Splits a string in to an array of strings

foreach $cone(@words) {
        print $cone;            # It print Thequickbrownfox
        }
print " \n";                    # put the cursor to the new line

@music=('White Album,Beatles',
        'Graceland,Paul Simon',
        'A Boy Named Sue, Goo Goo Dolls');
foreach $record (@music)     {
        print "record: $record \n";
        ($record_name, $artist)=split(/,/, $record);
        # Split record to record_name, artist. Print its
        print "record_name: $record_name \n";
        print "artist: $artist \n";
        }
 

------------------------------

VI. Using Modules

    Using modules, you can gain access to a large library of working code to help you write your programs.
At this time, more than 3500 modules are available with Perl.
To use a module in your Perl program, add use directive to Perl. For example, to include the Cwd module in your program, simply place the following somewhere in your code:        use Cwd;
 

#!/usr/bin/perl -w
use Cwd;
print "Your current directory is: ", cwd, "\n";
chdir 'c:\temp' or warn "directory c:\temp not accessible: $!";
print "You are now in: ", cwd, "\n";
 

-----------------------

VII. Function

A function is a group of code that can be called by name to do some work and then return some value. Perl's built-in functions are: print, sort, open, close, split, and so on.
To create user-defined subroutines in Perl by using the following syntax:
            sub subroutine_name     {
                  statement;
                 ...............;
            }

To invoke a subroutine (calling a subroutine), you can use either of the following syntax lines:

&subroutine_name();

or

subroutine_name();

Program example:

#!/usr/bin/perl -w
    sub world       {
        print "World!";
        }
    sub hello       {
        print "Hello, ";
        world();
        }

hello();
 

--------------------------------

VIII. Working With Files

# Open file openfile2. If openfile2 doesn't exist, error messages "Cannot open ..."
# and the program stop running
# command || is equal or, when open file error, the die command will be execute
open(MYTEXT, "openfile2") || die "Cannot open openfile2: $!\n";
print "openfile2 existing! the file listings:\n";

while (<MYTEXT>)    {
print $_;
}

#  This is the same while looping function:
# while (defined($a=<MYTEXT>))    {
#                                                       print $a;
#                                                       }

close(MYTEXT);

------------------------------------------------

# Append text line as a last line in the file.txt  file.
#!/usr/bin/perl -w
open (F, ">>file.txt") or die "file file.txt error: $!\n";
print F "\nOn the end";
close (F);
 

----------------------------------------------------------
 

# This is searching a word in all the files, in a directory.
#!/usr/bin/perl -w
use strict;
print "Directory to search: ";
my $dir=<STDIN>; chomp $dir;
# With command my,  $dir  to be a global variable
# When command my located in subroutine, its to be local variable
print "Pattern to look for: ";
my $pat=<STDIN>; chomp $pat;
my($file);

opendir(DH, $dir) or die "Cannot open $dir: $!";
while ($file=readdir DH)    {
    next if (-d "$dir/$file");
    # next is go back to while loop, because $dir/$file is a directory, it is try to get a file.
    if (! open(F, "$dir/$file") )      {
    # If the file cannot open, go back to while loop.
            warn "Cannot search $file: $!";
            next;
                                                      }
    while(<F>)            {
            if (/$pat/)                         {
                    print "$file: $_";
                                                    }
                                  }
    close(F);
    }
closedir(DH);
 

------------------

Resources
1. Perl in 24 Hours  by Clinton Pierce
2. The Perl Cookbook by Tom Christiansen, and Randal Schwartz
3. Perl Programmer's Reference by Martin C. Brown.

Hosted by www.Geocities.ws

1