Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Perl Tutorials - Herong's Tutorial Examples
Perl Tutorials - Herong's Tutorial Examples
Perl Tutorials - Herong's Tutorial Examples
Ebook537 pages

Perl Tutorials - Herong's Tutorial Examples

Rating: 0 out of 5 stars

()

Read preview

About this ebook

This Perl tutorial book is a collection of notes and sample codes written by the author while he was learning Perl language himself. Topics include introduction of ActivePerl; data types, variables and expressions; scalars, arrays, hash maps, and references; input/output and file systems; DBM files and MySQL access; socket communication; generating executables; XML::Simple and RPC:XML modules; LWP::UserAgent, HTTP::Request and SOAP::Lite modules; CGI, and IIS/Apache integrations. Updated in 2024 (Version v6.02) with minor updates.

For latest updates and free sample chapters, visit https://www.herongyang.com/Perl.
LanguageEnglish
PublisherLulu.com
Release dateMar 2, 2020
ISBN9781678187040
Perl Tutorials - Herong's Tutorial Examples

Read more from Herong Yang

Related authors

Related to Perl Tutorials - Herong's Tutorial Examples

Programming For You

View More

Reviews for Perl Tutorials - Herong's Tutorial Examples

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Perl Tutorials - Herong's Tutorial Examples - Herong Yang

    The Front Cover

    Perl Tutorials

    - Herong's Tutorial Examples

    Icon
    v6.02, 2024
    Herong Yang
    © 1995-2024 Herong Yang. All rights reserved.
    ISBN: 978-1-6781-8704-0

    This Perl tutorial book is a collection of notes and sample codes written by the author while he was learning Perl language himself. Topics include introduction of ActivePerl; data types, variables and expressions; scalars, arrays, hash maps, and references; input/output and file systems; DBM files and MySQL access; socket communication; generating executables; XML::Simple and RPC:XML modules; LWP::UserAgent, HTTP::Request and SOAP::Lite modules; CGI, and IIS/Apache integrations. Updated in 2024 (Version v6.02) with minor updates.

    Table of Contents

    About This Book

    Perl on Linux Systems

    Perl Installation on Linux Systems

    Running Perl Scripts on Linux Systems

    ActivePerl on Windows Systems

    What Is ActivePerl?

    Install ActivePerl on Windows Systems

    Running Perl Scripts on Windows Systems

    Data Types: Values and Variables

    Scalar Values and List Values

    Scalar Value Constructors

    Scalar Value Interpretation

    List Value Constructors

    Variables - Scalar, Array and Hash

    Using Scalar Variables

    Using Array Variables

    Using Hash Variables

    undef Value and Undefined Variables

    Expressions, Operations and Simple Statements

    What Is an Expression?

    Expression Evaluation Context

    Simple Statements and Modifiers

    User Defined Subroutines

    Declaring and Calling Subroutines

    SubParamList.pl - Example on Parameter List

    SubParamAlias.pl - Example on Parameters as Alias

    SubReturnValue.pl - Example on Return Values

    SubCalling.pl - Example on Calling Formats

    Perl Built-in Debugger

    Commonly Used Debugging Commands

    Debugging Tutorial Session

    Name Spaces and Perl Module Files

    Including Script Codes from Other Files

    do() Function - Including Script Files

    require() Function - Including Script Files

    package Statement - Switching Name Space

    BEGIN(), CHECK(), INIT() and END() Functions

    Defining Your Own Perl Module

    CalendarModule.pm - A Sample Perl Module

    Symbolic (or Soft) References

    Using Symbolic References

    $$name - Replacing Identifiers by Scalar Variables

    ${EXPR} - Replacing Identifiers by Expressions

    EXPR->* - The Dereference Operator

    $$$name - Nested Symbolic References

    Hard References - Addresses of Memory Objects

    \* - Creating Hard References

    Using Hard References

    $$name - Replacing Identifiers by Scalar Variables

    ${EXPR} - Replacing Identifiers by Expressions

    EXPR->* - The Dereference Operator

    $$$name - Nested Hard References

    \$b-\$a - Using Hard References in Other Operations

    Objects (or References) and Classes (or Packages)

    Basic Concepts of Classes and Objects

    Invoking Package Subroutines as Class Methods

    bless() - Converting References to Objects

    Invoking Package Subroutines as Object Methods

    Class Variables and Object Variables

    new() Method - Creating Objects by the Class

    CalendarClass.pm - A Perl Class Example

    Typeglob and Importing Identifiers from Other Packages

    Typeglob, Symbolic Table and Identifier Aliases

    Accessing Identifiers from Other Packages as Aliases

    Exporting and Importing Package Identifiers

    String Built-in Functions and Performance

    String Related Built-in Functions

    Performance of Perl substr() and index()

    Performance of Java substring() and indexOf()

    File Handles and Data Input/Output

    open() - Opening File Handles for Input and Output

    print() - Printing Output to File Handles

    - Reading Data from File Handles

    Open Files in Binary Mode

    binmode() - Opening Files for Binary Input

    binmode() - Opening Files for Binary Output

    Copy.pl - Copying Binary Files

    Bin2Hex.pl - Converting Binary Data to Hex Numbers

    Open Directories and Read File Names

    opendir() - Open Directory to Read File Names

    opendir.pl - Sample Program to Read Directories

    DirTree.pl - Displaying the Directory Tree

    DirGrep.pl - Searching Text in Directory Files

    File System Functions and Operations

    Built-in Functions to Work with the File System

    File Test Operators

    stat() - Returns File Statistics

    Image and Picture Processing

    Imager - Create and Save Image

    Imager - Draw Graphical Elements

    Imager - Convert Image File Format

    Imager::File::PNG - PNG File Format

    Install LIBPNG from Source Code

    Install Imager::File::PNG Manually

    Install PerlMagick from Source Code

    Using DBM Database Files

    dbmopen() - Opening DBM Files with Hash Variables

    DBM Database Example - English French Dictionary

    DBM Database Example - Book Records with Multiple Fields

    Using MySQL Database Server

    Installing Database Module for MySQL

    HelloMySQL.pl - My First Perl Program with MySQL

    Socket Communication Over the Internet

    What Is Socket Communication?

    connect() - Establishing a Socket Communication

    ReverseEchoer.pl - A Simple Socket Server Program

    SocketClient.pl - A Simple Socket Client Program

    gethostbyaddr() - Network Utility Functions

    Socket.pm - The Socket Module

    XML::Simple Module - XML Parser and Generator

    XMLin() and XMLout() Methods

    XML Parsing Options

    forcearray - Forcing Element Contents as Arrays

    suppressempty - Parsing Empty Elements

    keyattr - Namings Attributes as Keys

    XmlSimpleHash.pl - XML Hash Example

    XML Communication Model

    XML Messages over Socket Connections

    GameServer.pl - XML Communication Server Example

    GameClient.pl - XML Communication Client Example

    SOAP::Lite - SOAP Server-Client Communication Module

    What Is SOAP?

    What Is SOAP::Lite?

    SOAP::Transport::TCP - SOAP Server with TCP Protocol

    SoapTcpClient.pl - SOAP Client Example with TCP Protocol

    SOAP::Lite Tracing Functions

    SOAP::Transport::HTTP - SOAP Server with HTTP Protocol

    Perl Programs as IIS Server CGI Scripts

    Configuring IIS 5.0 for Perl Programs

    perl.exe vs. perlis.dll

    CGI (Common Gateway Interface)

    What Is Common Gateway Interface (CGI)?

    IIS Environment Variables

    QUERY_STRING - CGI Query String

    Calculator.pl - CGI Application Example

    XML-RPC - Remote Procedure Call with XML and HTTP

    What Is XML-RPC?

    Defining a Remote Method Call in XML

    Sending a Remote Method Call as a HTTP Request

    Defining Returning Values of a Remote Method Call

    Receiving Returning Values as a HTTP Response

    RPC::XML - Perl Implementation of XML-RPC

    What Is RPC::XML?

    RPC::XML::Server - XML-RPC Server Interface Class

    RPC::XML Client and Data Classes

    Installing NMake 1.5

    Installing RPC::XML Module

    RpcXmlServer.pl - RPC::XML Server Sample Program

    RpcXmlClient.pl - RPC::XML Client Sample Program

    Sending Arrays with Remote Method Calls

    Integrating Perl with Apache Web Server

    Downloading Apache HTTP Server 2.2.25 for Windows

    Installing Apache HTTP Server 2.2.25 on Windows

    Publishing HTML Documents as Web Pages

    Starting and Stopping Apache Server

    Running Perl Scripts in cgi-bin

    printenv.pl - Testing Perl CGI Environment

    500 Internal Server Error

    cgi-lib.pl - The Standard Library for CGI Scripts

    ReadParse() - Parsing Web Form Input Values

    Running Perl Scripts in htdocs

    CGI.pm Module for Building Web Pages

    What Is CGI.pm?

    Generating HTML Document with CGI.pm

    Retrieving Query Parameters and Headers

    Retrieving Environment and Script Information

    Redirecting Browser to a URI

    Refresh http-equiv Meta Tag

    What Is CGI::Cookie?

    Retrieving and Setting HTTP Cookies

    LWP::UserAgent and Web Site Testing

    What Is LWP::UserAgent?

    What Is HTTP::Response?

    What Is HTTP::Request?

    LWP-UserAgent-GET.pl - Sending a GET Request

    LWP-UserAgent-GET-Redirect.pl - Following HTTP Redirects

    http-equiv=Refresh Meta Tag not Followed

    LWP-UserAgent-POST.pl - Posting Form Data

    post() Method not Following Redirect Location

    LWP-UserAgent-POST-Redirect.pl - Posting with Redirects

    What Is HTTP::Cookies?

    LWP-UserAgent-Request.pl - GET, POST and Cookies

    LWP-UserAgent-Request.pl - Login to facebook.com

    HTTP::Cookies save() not Saving Temporary Cookies

    LWP-UserAgent-Request-Cookies.pl - Sending Request with Cookies

    Converting Perl Script to Executable Binary

    Perl Script Conversion Tools

    Installing Perl Dev Kit (PDK)

    Running PerlApp to Convert *.pl to *.exe

    Managing Perl Engine and Modules on macOS

    Perl Version Pre-Installed on macOS

    Install Xcode Command Line Tools

    Configure CPAN Shell

    Install Perl Module from CPAN

    Install Perl Module from Source Code

    Archived Tutorials

    Archived: Install ActivePerl v5.18.1 on Windows Systems

    Archived: Install ActivePerl v5.8.8 on Windows Systems

    References

    Keywords: Perl, Script, Language, Tutorial, Example

    Perl Tutorials - Herong's Tutorial Examples

    ∟ About This Book

    This section provides some detailed information about this book - Perl Tutorials - Herong's Tutorial Examples.

    Title: Perl Tutorials - Herong's Tutorial Examples

    Author: Herong Yang - Contact by email via herong_yang@yahoo.com.

    Category: Perl/Tutorial

    Version/Edition: v6.02, 2024

    Number of pages in PDF format: 333

    Description: This Perl tutorial book is a collection of notes and sample codes written by the author while he was learning Perl language himself. Topics include introduction of ActivePerl; data types, variables and expressions; scalars, arrays, hash maps, and references; input/output and file systems; DBM files and MySQL access; socket communication; generating executables; XML::Simple and RPC:XML modules; LWP::UserAgent, HTTP::Request and SOAP::Lite modules; CGI, and IIS/Apache integrations. Updated in 2024 (Version v6.02) with minor updates.

    Keywords: Perl, Script, Language, Example, Code, Tutorial, Book.

    Copyright:

    This book is under © 1995-2024 Herong Yang. All rights reserved.

    Material in this book may not be published, broadcasted, rewritten or redistributed in any form.

    The example codes is provided as-is, with no warranty of any kind.

    Revision history:

    Version v6.02, 2024. Minor updates.

    Version v6.00, 2020. Added tutorials for macOS and Linux.

    Version v5.50, 2019. Updated with Perl v5.26.1.

    Version v5.30, 2014. Added tutorials on CGI.pm and LWP::UserAgent.

    Version v5.00, 2005. Added tutorials on XML-RPC.

    Version v4.00, 2002. Added tutorials on SOAP.

    Version v3.00, 1999. Added tutorials on classes.

    Version v2.00, 1996. Added tutorials on DBM files.

    Version v1.00, 1995. First edition.

    Web version: https://www.herongyang.com/Perl - Provides free sample chapters, latest updates and readers' comments. The Web version of this book has been viewed a total of:

    2,143,629 times as of December 2023.

    2,090,689 times as of December 2022.

    1,969,004 times as of December 2021.

    1,836,525 times as of December 2020.

    1,730,429 times as of December 2019.

    1,642,156 times as of December 2018.

    1,547,354 times as of December 2017.

    1,433,821 times as of December 2016.

    1,307,643 times as of December 2015.

    1,162,501 times as of December 2014.

    979,141 times as of December 2013.

    813,834 times as of December 2012.

    650,091 times as of December 2011.

    490,036 times as of December 2010.

    356,604 times as of December 2009.

    207,629 times as of December 2008.

    137,317 times as of December 2007.

    92,461 times as of December 2006.

    PDF/EPUB version: https://www.herongyang.com/Perl/PDF-Full-Version.html - Provides information on how to obtain the full version of this book in PDF, EPUB, or other format.

    Perl Tutorials - Herong's Tutorial Examples

    ∟ Perl on Linux Systems

    This chapter provides tutorial examples and notes about using Perl on Linux systems. Topics include verifying Perl installation; running Perl scripts in different ways; making a Perl script file executable.

    Perl Installation on Linux Systems

    Running Perl Scripts on Linux Systems

    Takeaways:

    Perl is included in Linux systems. There is no need to install it manually.

    The best way to run a Perl script file on a Linux system is to include #!/usr/bin/perl as the first line in the file and change its mode to be executable.

    Perl Tutorials - Herong's Tutorial Examples

    Perl on Linux Systems

    ∟ Perl Installation on Linux Systems

    This section describes how to verify Perl installation on Linux systems. The 'perl -v' command returns which version of Perl is installed on the Linux system.

    If you are running a Linux system, Perl is already installed on the system. No need to do any extra installation work.

    Here is what I did to verify the Perl installation on the Linux server of my Internet service provider in 2019:

    /home/herong$ which perl

    /usr/bin/perl

     

    /home/herong$ perl -v

    This is perl 5, version 26, subversion 1 (v5.26.1) built for

    x86_64-linux-gnu-thread-multi (with 67 registered patches,

    see perl -V for more detail)

     

    Copyright 1987-2017, Larry Wall

     

    Perl may be copied only under the terms of either the Artistic License

    or the GNU General Public License, which may be found in the Perl 5

    source kit.

     

    Complete documentation for Perl, including FAQ lists, should be found

    on this system using man perl or perldoc perl.  If you have access

    to the Internet, point your browser at http://www.perl.org/, the Perl

    Home Page.

     

    /home/herong$ man perl

    PERL(1)          Perl Programmers Reference Guide          PERL(1)

     

    NAME

      perl - The Perl 5 language interpreter

     

    SYNOPSIS

      perl [ -sTtuUWX ]      [ -hv ] [ -V[:configvar] ]

          [ -cw ] [ -d[t][:debugger] ] [ -D[number/list] ]

          [ -pna ] [ -Fpattern ] [ -l[octal] ] [ -0[octal/hexadecimal] ]

          [ -Idir ] [ -m[-]module ] [ -M[-]'module...' ] [ -f ]

          [ -C [number/list] ]      [ -S ]      [ -x[dir] ]

          [ -i[extension] ]

          [ [-e|-E] 'command' ] [ -- ] [ programfile ] [ argument ]...

     

      For more information on these options, you can run perldoc perlrun.

     

    GETTING HELP

      The perldoc program gives you access to all the documentation that

      comes with Perl.  You can get more documentation, tutorials and

      community support online at .

    ...

    As you can see from the output, this Linux system has Perl 5.26.1 installed and ready to use.

    Even on older versions of Linux systems, Perl was included in Linux distribution packages and installed automatically. Here is an example captured on the Linux server of my Internet service provider in 2009

    /home/herong$ which perl

    /usr/local/bin/perl

     

    /home/herong$ perl -v

    This is perl, v5.8.8 built for i486-linux-gnu-thread-multi

     

    Copyright 1987-2006, Larry Wall

     

    ...

    Here is another example captured on my old PC running a Linux 2.0.30 system in 1999:

    /home/herong$ which perl

    /usr/bin/perl

     

    /home/herong$ perl -v

    This is perl, version 5.004_03

     

    Copyright 1987-1997, Larry Wall

     

    ...

    Perl Tutorials - Herong's Tutorial Examples

    Perl on Linux Systems

    ∟ Running Perl Scripts on Linux Systems

    This section provides a tutorial example on how to run Perl scripts on Linux systems. To make a Perl script file executable, you need to add '#!/usr/bin/perl' to the beginning of the script.

    There are many ways to run Perl scripts on Linux:

    1. Run the perl command with the Perl script included in the command line. For example, enter the following command line in a shell window:

    /home/herong$ perl -e print 'Hello world!';

    Hello world!

    Note that the above command will not work in some shell windows. For example, in a bash shell window, you will get the following error, because the ! is a reserved character to access an event in the command history.

    /home/herong$ perl -e print 'Hello world!';

    -bash: !': event not found

    To avoid the problem, you can run the above command a sh command window:

    /home/herong$ sh

    $ perl -e print 'Hello world!';

    Hello world!$

    Or you can protect ! using escape sequence:

    /home/herong$ perl -e print \"Hello world\!\n\";

    Hello world!

    Or you can use single quotes ('...') to protect the entire Perl script from the shell:

    /home/herong$ perl -e 'print Hello world!\n;'

    Hello world!

    Here is another example of running a Perl script in a single command line:

    /home/herong$ perl -e for (\$i=0; \$i<10; \$i++) {print \"\$i\n\";}

    0

    1

    2

    3

    4

    5

    6

    7

    8

    9

    Note that dollar sign ($) used for Perl scalar variables are also shell reserved characters, we need to use escape sequences to protect them.

    Also note that double quote (") is used to put the entire script code as one command line parameter. Any double quote inside the program needs to be protected as (\").

    Or you can use single quotes ('...') to protect the entire Perl script from the shell:

    /home/herong$ perl -e 'for ($i=0; $i<10; $i++) {print $i\n;}'

    0

    1

    2

    3

    4

    5

    6

    7

    8

    9

    Including Perl script in the command line is quick and easy. But you can only run scripts that are small enough to fit into one command line.

    2. Run the perl command with the Perl script supplied from the standard input stream. For example, enter perl in a command window. Then enter the script code followed by Control-D, which is the End Of File (EOF) indicator:

    /home/herong$ perl

    $s=0;

    for ($i=0; $i<10; $i++) {

      $s+=$i;

    }

    print $s\n;

    ^D

     

    45

    Obviously, you can enter a much longer script in this way. But the program is not save permanently.

    3. Run the perl command with the Perl script supplied in a file. For example, enter the following Perl script in a file called hello.prg:

      print Hello world!\n;

    Then enter the following command in a command window:

    /home/herong$ perl hello.prg

    Hello world!

    4. Run Perl script files as commands. You can do this, only if you insert a special line at the beginning of your script file: #!/usr/bin/perl, and assign execution permission to the script file. This special line represents the Perl installation location on the file system.

    For example, enter the following script in a file called hello.pl:

    #!/usr/bin/perl

      print Hello world!\n;

    Then assign execution permission and enter the script file name to run it:

    /home/herong$ chmod a+x hello.pl

    /home/herong$ ./hello.pl

    Hello world!

    It works! And this is the best way to run Perl scripts on Linux systems.

    Perl Tutorials - Herong's Tutorial Examples

    ∟ ActivePerl on Windows Systems

    This chapter provides tutorial examples and notes about using ActivePerl on Windows systems. Topics include features of ActivePerl; installing ActivePerl on Windows systems; running Perl scripts with ActivePerl.

    What Is ActivePerl?

    Install ActivePerl on Windows Systems

    Running Perl Scripts on Windows Systems

    Takeaways:

    To use Perl script on a Windows system, you need to download and install ActivePerl community version.

    The best way to run a Perl script file on a Windows system is to name the file with .pl extension and associate it with ActivePerl program.

    Perl Tutorials - Herong's Tutorial Examples

    ActivePerl on Windows Systems

    ∟ What Is ActivePerl?

    This section describes what is ActivePerl - a free Perl engine for Windows, Linux and other platforms developed by ActiveState.

    ActivePerl is a Perl engine developed by ActiveState supporting multiple platforms including Windows and Linux. ActiveState provides, free to the community, the ActivePerl binary packages, which include:

    Perl, the binary core distribution of the Perl engine.

    The Perl Package Manager, for installing Perl extension modules.

    Complete documentation.

    The Windows version of ActivePerl also includes:

    PerlScript, an ActiveX scripting engine, like JavaScript or VBScript, with a Perl brain.

    Perl for ISAPI, an IIS plug-in that runs Perl CGI scripts faster.

    PerlEz, for embedding Perl the easy way.

    ActiveState also offers a non-free version, ActivePerl Enterprise, with extra features.

    For more information on ActivePerl, visit ActivePerl home page at ActiveState.com/ActivePerl.

    Perl Tutorials - Herong's Tutorial Examples

    ActivePerl on Windows Systems

    ∟ Install ActivePerl on Windows Systems

    This section provides a tutorial example on how to install ActivePerl on a Windows computer.

    If you are using a Windows system and want to run Perl scripts, you can install the free binary package, ActivePerl, provided by ActiveState. Here is what I did to install ActivePerl on my Windows computer.

    1. Go to https://www.activestate.com/products/perl/, I see the ActiveState Perl download page.

    2. Click on Download Perl 5.32 button. I see the login page.

    3. Log in with your ActiveState account, or sign up a new account. I see the new project page.

    4. Select Perl > 5.34.0 > Windows 10 and click Create Runtime. I see the Download & Install Runtime comment.

    5. Copy the command and run it in a command window:

    herong> powershell -Command \

      "& $([scriptblock]::Create((New-Object Net.WebClient).DownloadString \

      ('https://platform.activestate.com/dl/cli/pdli01/install.ps1'))) \

      -activate-default herong/Perl-5.34.0-Windows"

     

    - Preparing Installer for State Tool Package Manager... Done

    - Installing State Tool Package Manager

     

    The State Tool lets you install and manage your language runtimes.

     

    ActiveState collects usage statistics and diagnostic data about failures.

    By using the State Tool Package Manager you agree to the terms of

    ActiveState’s Privacy Policy, available at:

    https://www.activestate.com/company/privacy-policy

     

    - Downloading State Tool version 0.32.0-SHA7474314...  Done

    - Installing State Tool to

      C:\Users\herong\AppData\Local\ActiveState\StateTool\release... Done

    4. Open a new command window, and type in perl -v. If you see the following output, your installation is ok.

    herong> perl -v

     

    This is perl 5, version 34, subversion 0 (v5.34.0) built

      for MSWin32-x64-multi-thread

     

    Copyright 1987-2021, Larry Wall

     

    Binary build 34.0r4 provided by ActiveState http://www.ActiveState.com

    Built Wed Nov 17 04:20:44 2021

     

    Perl may be copied only under the terms of either the Artistic License

    or the GNU General Public License, which may be found in the Perl 5

    source kit.

     

    Complete documentation for Perl, including FAQ lists, should be found on

    this system using man perl or "perldoc

    Enjoying the preview?
    Page 1 of 1