Perl Programming Language

By

First published on September 9, 2019. Last updated on February 13, 2020.

Perl Programming Language

By

First published on September 9, 2019. Last updated on February 13, 2020.




Table of Contents



This course introduces the Perl programming language, then presents concepts such as variable and provides examples.


This course introduces the Perl programming language, then presents concepts such as variable and provides examples.




  1. 1 Introduction to Perl



    First published on . Last updated on February 16, 2020.

    Perl is a programming language that is good at processing text. (Some folks might call it a scripting language, but it doesn’t really matter for our purposes). Perl became extremely popular in the early days of the world wide web for writing scripts to make websites do things. Its ability to work with text is one of its chief advantages over other languages.

    Perl is both a somewhat flexible and fussy language, unlike some other languages such as Ruby. Perl gives you many ways to do something, yet it can be very particular about some things, especially if you set it to be so. Also, PERL has changed over the years, so some earlier program examples you find might not work with current environments. However, for some tasks, Perl is the right tool for the job, and there is also a lot of legacy code written in Perl.


  2. 2 Perl Hello World



    First published on . Last updated on February 6, 2021.

    Let’s begin with a simple Perl program. It will only display a simple message but contains several important parts.

    [code lang=”perl”]

    #!/usr/bin/env perl

    use strict;

    use warnings;

    print "Hello World!\n";

    [/code]

    (On Windows, you may need to replace the first line with:

    #!C:\Perl\bin\perl.exe

    The first line tells your computer to run your program within the Perl environment. The next lines tell Perl to require strict coding and show warnings for violations.These lines are optional but recommended for learning.

    The final line tells Perl to print your greeting message to the output device (which is probably your screen).

    Notice how most of the lines end in semicolons. This tells Perl that you intend the line to end there. This is useful when you need to write a long line of code that actually takes up several lines of screen space.

    There are several ways to run your Perl script.

    You can save your code in a file that ends with “.pl”, which tells the computer that this is a Perl file.

    Run a Perl program on a Unix or Linux machine by typing:

    perl yourfilename.pl

    Or you can enter and  run your Perl code at an online development such as ideone. (Beware the some environments might run different versions of Perl, so you may need to tweak your code to run on them.)

    If you are having trouble, see the Troubleshooting lesson.


  3. 3 Comments and Pseudocode



    First published on . Last updated on September 9, 2019.

    Comments are useful for explaining what code does, to jog your memory later or help another programmer understand your code. Comments can be helpful for identifying sections of code, or for “turning off” individual lines of code for purposes of testing or options.

    You can add comments in your code by preceding them with a “#”, which can appear at the beginning of an entire line of comments, or after the semicolon of a functional line of code.

    You can also use comments to design and organize your program at a high level, before you write any actual functional code. This allows you to brainstorm quickly.


  4. 4 Variables



    First published on . Last updated on February 16, 2020.

    The most simple type of variable in Perl are single value variables called scalers. They are used for numbers or single strings of text. Their names should begin with “$”.

    In Perl, you should declare your variables the first time you use them. For example:

    my $year = 2019;

    If you are assigning a string (e.g. text), the string must be placed in quotes:

    my $city = "Nairobi";

    Arrays are used for variables that contain multiple values. In Perl, arrays should begin with “@”, for example:

    my @fruits = ("apple", "banana", "orange");

    Arrays are referenced by item number (starting with 0):

    print @fruits[1];

    will display:

    banana

     


  5. 5 Searching and Parsing Text



    First published on . Last updated on February 6, 2021.

    A key strength of Perl is that it has lots of built-in tools for searching and parsing text. This is why is it so popular in both the humanities and biotechnology (genes are expressed in strings of letters).

    Below is an example that you can try out. First, some text to search is provided and placed in the variable “$speechtext”.

    The a search condition is specified. =~ means contains. The “\” (escape character) is added to tell the ideone environment that the ~ really is intended as a ~. (Escaping the tilde is only required in some environments).

    The desired string is placed in “//” characters.

    The if control structure test the search condition and then alerts the user if the condition is or is not met.

    #!/usr/bin/perl6
    
    my $speechtext = "Four score and seven years ago...";
    
    if ($speechtext =~ /seven/ ) {
       print "My text item is found.\n";
    } else {
       print "My text item is not found.\n";
    }
    

    Below is a program to count how many matches there are in a file.

    use strict;
    use warnings FATAL => 'all';
    
    #### BANNER ####
    
    print "\n=================================\n";
    print "\n DOCUMENT SEARCHING PROGRAM      \n";
    print "\n=================================\n\n";
    
    #### CREATE SOME TEXT DATA ####
    
    my $afile = 'Abe, Bill, Cathy, Darlene, Eva, Darlene, Bill';
    
    #### WRITE FILE ####
    {
        open my $fh, '>', 'afile.txt';
        print {$fh}  $afile. "\n";
        close $fh;
    }
    
    #### READ & PRINT CONTENTS ####
    {
        #### ENTER SEARCH TERM HERE:
        
        my $textitem = "Darlene";
        
        #### OPEN FILE ####
        
        open my $fh, '<', 'afile.txt';
        my ($filetext) = <$fh>;
        print "Data in file: ". $afile . "\n\n";
        
        #### SEARCH ####
    
        if ($filetext =~ /$textitem/ ) {
            print "My search term $textitem is found.\n\n";
        } else {
            print "My search term $textitem is not found.\n\n";
        }
    
        #### COUNT MATCHES ####
    
    
        my @matches = ($filetext =~ /$textitem/g);
        my $mymatches = @matches;
        print "My search term $textitem is matched $mymatches time(s).";
    
        close $fh;
    }

    Below is a program that attempts to measure the strength of a relationship between to people by listing files that in which both of their names are present.

    use strict;
    use warnings FATAL => 'all';
    # use autodie qw(:all);
    
    
    #### BANNER ####
    
    print "\n======================================\n";
    print "\n DATA MINING PROGRAM -- RELATIONSHIPS \n";
    print "\n======================================\n\n";
    
    my $minerun = int(rand(100000));
    
    print "Mining Run # $minerun \n\n";
    
    #### DATA ####
    
    my $meeting_attendees_1891 = 'Abe, Bill, Cathy, Darlene';
    my $meeting_attendees_1892 = 'Bill, Jean';
    my $meeting_attendees_1893 = 'Abe, Bill, Pat, Darlene';
    
    
    #### CREATE AND WRITE DATA TO FILES ####
    
    ## In a real workflow, the files would already exist. ##
    ## Also, a loop would be more elegant, but trickier. ##
    
    {
        open my $fh, '>', 'meeting_attendees_1891.txt';
        print {$fh}  $meeting_attendees_1891 . "\n";
        close $fh;
    }
    
    {
        open my $fh, '>', 'meeting_attendees_1892.txt';
        print {$fh}  $meeting_attendees_1892 . "\n";
        close $fh;
    }
    
    {
        open my $fh, '>', 'meeting_attendees_1893.txt'; # cfile is reserved
        print {$fh}  $meeting_attendees_1893 . "\n";
        close $fh;
    }
    
    #### PRINT LIST OF FILES ####
    
    ## This is somewhat manual, due to limit of this interface.
    
    ## Set up an array with the file names
    
    my @meetingfiles = ("meeting_attendees_1891", "meeting_attendees_1892", "meeting_attendees_1893");
    
    ## Run through the array values with a loop
    
    print "FILES:\n\n";
    
    for (my $i=0; $i <= 2; $i++) {
    
    print "$meetingfiles[$i]" . ".txt\n";
    
    }
    
    #### READ DATA FROM FILES ####
    
    ## Relationship Criteria ##
    
    my $person1 = "Darlene"; my $person2 = "Bill";
    
    ## Mine The Data ##
    
    print "\nMY CRITERIA RESULTS:\n\n";
    {
        for (my $i=0; $i <= 2; $i++) {
            # print "$i\n";
    
            open my $fh, '<', $meetingfiles[$i] . ".txt";
            my ($filetext) = <$fh>;
    
            if ($filetext =~ /$person1/ and $filetext =~ /$person2/ ) {
            print "Both $person1 and $person2 are found in $meetingfiles[$i].txt\n";
            } 
            close $fh;
        
        }
    }

    Further Reading

     


  6. 6 Further Reading



    First published on . Last updated on February 16, 2020.


  7. 7 Troubleshooting



    First published on . Last updated on February 16, 2020.

    Hopefully your program ran as desired. However, real life is often not that easy. Here are some suggestions for troubleshooting:

    1. Examine any warning messages. Sometimes they contain the line number of where there is problematic code.
    2. Checking your spelling.
    3. Make sure that you are not missing may semicolons.
    4. Check to see if all of your variables have been declared.
    5. Make sure special use characters are escaped with a backslash. For example, an “n” that is mean to indicate next line should be escaped, i.e. “\n”. Sometimes the “~” character or quotes inside of quotes also need to be escaped.
    6. Advanced: make sure the privileges for the file is executable (look up how to do this for your operating system; check information about your operating systems how to do so.)


Content is copyright the author. Layout is copyright Mark Ciotola. See Corsbook.com for further notices.