Creating CGI Scripts Using PERL. Simple and compound operators


A convenient system for organizing an online auction server.

Program features:

  • User registration.
  • Confirmation email.
  • Password protection.
  • Automatic closing of the auction.
  • Built-in search engine.
  • Forgotten password recovery.
  • Built-in help system.
  • Unlimited number of categories and subcategories.
  • Customizable appearance.
  • Trading history for each product.
  • Administrator interface.
  • View closed auctions.
  • Sorting auctions.
  • Ability to view hot auctions and those that will close soon.
  • Support of the mail form for questions to the server administrator.
  • And much more...
  • DirectMailer 1.6.9 1.6.9

    Edit

    If you do not have an ftp client on your Unix server or for some reason you do not want to give your users ftp access to edit pages, then you can use this script. It allows your users to edit their page on the server using a Web form.

    WebCode Chat v1.0

    Plain Text Counter

    Simple text counter. Requires SSI. Can be used for a single page or for the entire site. The program automatically creates log file for each page of the site separately.

    Josephina v1_final

    A full-fledged commercial set of scripts in Perl for creating the Internet service “Bulletin Board”.
    This web-system allows very by simple means and without special knowledge create your own online bulletin board. The system has user-friendly interface administrator, which allows you to manage everything that happens on the board by simply selecting the necessary items directly in your Internet browser, without knowledge of programming languages ​​and administrator skills.
    You can apply this system to:
    Organize a business on the Internet.
    Increase its traffic to an existing Internet project, supplement it with a new service, and make it more valuable for visitors.

    System requirements.
    Hosting operating system: Free BSD or Open BSD or Linux.
    Hosting space: 0.1 mb / category
    Support for CGI scripts in Perl.

    Please note: the message board does not require MySQL and uses only one, the most common module (CGI) of the perl language.
    You don't need to hire an administrator to set up a message board for your hosting, or spend time learning programming languages ​​and database administration tools.

    Fluid Dynamics Search Engine, V 2.0.0.0030

    A script that searches the server. The script is very easy to install, although it is much more difficult to configure, especially without knowing English. It has great amount settings, everything is configured via the web interface. Requires MySQL, so if your server does not allow you to use this DBMS, the script will be useless for you.

    SSI Random Text Displayer v1.01

    With this program you can always display something new on your page, since it is designed for random display of text. For the program to work, you must create a database that will contain all your quotes (hints, jokes, etc.), and the program will randomly select one of them and display it on your page.

    Stat Lite v1.0

    Stat Lite is a set of perl scripts that
    will help you get statistics of your
    virtual web server. First of all
    this software product is aimed at
    small web servers with a number
    no more than 1000 visitors per day.

    With this package you can:


    • view statistics for the required
      month and year
    • statistics of hosts and hits
    • store summary statistics for the entire
      script usage period
    • view statistics via the web
    • view reports in text and
      graphical form(graphs)

    For the script to work you need
    compiled Perl with GD module (graphical
    library).

    Free version. The only condition
    installation on your site - availability of a link to
    author at the bottom.

    Mailing List Manager v4.0 (NT)

    This program is designed to manage mailing lists. The program has a convenient administrative interface, with which you can easily send a letter to any of your subscribers individually, edit the list (delete/change address). In addition, subscribers (visitors) can independently add themselves to the mailing list or unsubscribe. In order to add your address to the mailing list, the visitor must fill out a short form in which you must enter your email address, your name and select (from the list) a subscription topic.

    Andrey Novikov

    What is Perl?

    Perl is an interpreted language created by programmer Larry Wall for processing large texts and files and stands for Practical Extraction and Report Language. With Perl, for example, you can create a script that opens one or more files, processes the information, and writes the results.

    With the invention of the World Wide Web, Perl proved to be an excellent tool for interacting with web servers through the Common Gateway Interface (CGI). Perl commands can easily retrieve data from HTML forms or another source and do something with them.

    How Perl processes form data

    Perl is flexible enough to handle input. For example, if a user enters information into a registration form, the Perl script can process it in many ways, such as:

    • add them to a text file,
    • enter them into the database,
    • paste them into an email,
    • add them to an existing web page,
    • create a new web page,
    • display them in the browser window.

    Some of these examples are discussed in our lesson.

    How web pages are generated on the fly

    What's most impressive is that Perl can be used to create web pages on the fly in response to a user request or action. New page May be

    • thanks for filling out the form
    • confirmation page with the ability to edit
    • requesting additional data
    • result of a database query or search query

    This feature brings true interactivity to your site. Such scripts will allow the web server to automatically respond to a specific set of user requests, providing data in the form required by the user.

    What is the difference between a program and a script?

    Before you start working with Perl, you need to understand the difference between a program and a script. Both of them use a set of instructions to perform a specific task, but the program is compiled into an efficient binary format, allowing it to execute quickly on a specific platform, while the script is stored in its original text format.

    Due to the fact that scripts are much shorter than programs, they also execute quite quickly.

    Due to the fact that the script does not need to be compiled before launching, it becomes an excellent tool for quickly creating and making corrections in the development of interactive parts of a node.

    Alternatives to Perl

    There are several alternatives to using Perl:

    • C, Visual Basic - more traditional computer languages ​​for processing input data. Must be compiled for a specific platform.
    • ActiveX - enabling software components running in the browser.
    • JavaScript, VBScript - provide some interactivity to HTML pages that HTML cannot provide.
    • Cold Fusion is a third-party program for linking forms with databases.
    • PHP/FI is another third party program for linking forms to databases.

    Despite this, Perl is by far the simplest, fastest, and at the same time very powerful way to add interactivity to your site.

    What you need to run Perl

    To run Perl, your system will need several components:

    1. A script written by you or offered to you by someone else, saved in a text file.
    2. Perl interpreter. Any Perl script contains the path to this program in the first line.
    3. The web page from which this script will be launched. It can contain a form or just a link if the script does not require input data.
    4. Web server. The interaction between the web page and the script is carried out by the server. Therefore, you must have access to a web server with the ability to write and run scripts on it.

    Where to get Perl

    There are many different places where you can get information about the latest versions of Perl.

    • General information about Perl - http://www.perl.com/perl/index.html
    • Perl for UNIX - http://www.perl.com/perl/info/software.html
    • Perl for Win32 - http://ntperl.hip.com

    Stages of creating a script

    Once you have installed the necessary software on your computer, there are a few steps you need to take to get Perl running on your node:

    1. Create a form to call the script.
    2. Create the script itself.
    3. Debug the script. Check for errors (if possible, it is better to check all possible paths of program execution).
    4. Place the script on the server and do not forget to give it execution rights.
    5. Link the script to the form by inserting its name into the action parameter of the form tag. For example:
    1. Make sure that the script works correctly with the form.

    Main parts of a Perl script

    In general, any Perl script consists of four key parts:

    1. Tincture. The first part of the script necessarily starts the interpreter and sets the variables used in the body of the script. To run the interpreter, you need to know the correct path to the program.
    2. Reading input data. This part “reads” and stores the input data in variables in a form convenient for processing. This part is usually the same across all scripts.
    3. Processing input data. This part processes the entered data accordingly. It can be simple (about 5 lines) or very complex (more than 1000 lines) depending on the task being performed.
    4. Output of results. The user usually expects some kind of response to his actions. This part is quite easy to implement.

    Example script with a form

    Let us now consider the steps we have described using a specific example. You are not required to understand every line of the script, they will all be explained below.

    Step 1 - Creating the Form

    For simplicity, let's create a form that contains only one field and allows the user to register his name. Let's write the following text in the editor:

    Test Form Enter your name:

    Save the file to disk.

    Step 2 - Creating a Script

    The script below takes the entered data, saves it in a file and displays a message containing a link to the file with the saved name. Type the program text in the editor and save it in the testform.pl file in the cgi-bin directory of your web server. Make sure that the first line of the program contains the correct path to the interpreter program (to locate the program on UNIX, use the which perl command; on Windows, search for the file perl.exe). Also make sure that the path to the output file is the correct path to the document storage area of ​​the web server. Finally, correct the URL to match your server's address.

    #!/usr/local/bin/perl #<-- ПРОВЕРЬТЕ ЭТО # Read and parse input from the web form read(STDIN, $buffer, $ENV{"CONTENT_LENGTH"}); @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%()/pack("C", hex($1))/eg; $value =~ s///g; $input($name) = $value; ) # Save the user output in a file $targetfile = "/usr/local/www/htdocs/names.html"; #<-- ПРОВЕРЬТЕ ЭТО open (NAMEFILE, ">>$targetfile"); print NAMEFILE "

    Name: ",$input("user_name"),"

    \n"; print NAMEFILE "


    \n"; close (NAMEFILE); # Send a message back to the user print "Content-Type: text/html\n\n"; print "

    Thank you for filling out the form

    \nClick "; print "here"; #<-- ЗАМЕНИТЕ ЭТО print ", чтобы увидеть Ваш ввод.\n";

    Step 3 - Testing the Script

    Having checked the script visually for errors - the absence of ";" at the end of lines, the presence of unpaired brackets and quotes, etc., run the script to check directly from the command line, first going to the cgi-bin directory. Here are some examples of how this is done:

    ./testform.pl /usr/local/bin/perl testform.pl c:\perl\perl.exe testform.pl

    If the script contains errors, you will see a message like

    syntax error at testform.pl line 18, near "open" Execution of testform.pl aborted due to compilation errors.

    In this case, check the text next to the specified line. Remember that the cause of the error may be several, sometimes quite many, lines higher. Save the corrected script and test it until it produces the correct output:

    Content-Type: text/html

    Thank you for filling out the form

    Click here to see your entry.

    Step 4 - Testing the Script with the Form

    If the script works on its own, you can test it with the form:

    1. Make sure the web server is running.
    2. Launch your browser.
    3. Type the URL where your form is located (note that the line must start with http://, not file://.
    4. Enter your name in the form field and click the "Register" button.
    5. You should see a message like this:

    Thank you for filling out the form
    Click here to see your input.

    This is the page generated by the script on the fly. If you receive a server error message, check that the script is located correctly and the value of the action parameter in the form tag is correct.

    1. If you see a correctly generated page, click on the link. You should see a new page created by the script that looks something like this:

    Name: Novikov

    If you don't see this, check that the path in the $targetfile variable is correct and the URL in the penultimate line of the script is correct. Otherwise, the form and script work correctly together. You have successfully created your first web application.

    Discussion: Setting up the script

    As already mentioned, the first part of the script contains settings that include several elements. The first line specifies the path to the interpreter program:
    #!/usr/local/bin/perl for UNIX
    or
    \Program Files\Perl5\perl.exe for Win32

    Also, at the beginning of the script, for convenience, you can place a comment about what this script is intended for.

    Comments can be located anywhere in the program and begin with the # symbol:
    # This is a comment or
    open(NAMEFILE, ">$testfile"); #Open the file for writing...

    It is also a good practice to define all constants and global variables at the beginning of the script. (I advise you to register all paths as variables, especially if the program contains more than 50 lines, for the convenience of changing the location of files). For example:
    $homepage = "http://server_name/home/index.html";

    All regular variables in Perl begin with a $ character. There are many other kinds of variables, such as arrays and the like.

    All lines of the program except the first and comments must end with ";".

    Discussion: Reading data from a form

    Now we need to "read" the user input into Perl variables. After the user clicks the Submit button on the form, the browser sends the server the name of the script and the data taken from the form. The data is passed to the script on standard input.

    Let's assume that the form contains the following fields:

    In this case, the data will be sent to the script in the following format:
    user_name=Andy+Novikov&co_name=TeleSputnik&phone=(812)+123-45-67

    The Perl script must parse this string piece by piece and store it in variables for further processing. The lines that perform these actions are quite standard:
    read(STDIN, $buffer, $ENV("CONTENT_LENGTH"));

    This line reads data from standard input and places it in the $buffer variable. The length of the string is passed to the script via the CONTENT_LENGTH environment variable.

    Once the data is placed in the $buffer variable, you can split it into separate variables with their corresponding values:
    @pairs = split(/&/, $buffer);

    Now we have an @pairs array with the following string variables:
    user_name=Andy+Novikov
    co_name=TeleSputnik
    phone=(812)+123-45-67

    Now we need to break these lines into parameter-value pairs:
    foreach $pair (@pairs) ( ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; # replace pluses with spaces $value =~ s/%() /pack("C", hex($1))/eg; $value =~ s///g; $input($name) = $value; )

    This way you get an array of variables, the index of which is the value of the name parameter of the form field, and the value is the data entered in the corresponding field.

    Discussion: What to do with the data?

    The next step is data processing. But how? It all depends on what you want to do with the data. In our example, we create a new HTML document based on the received data. Below we will look at some simple examples of what can be done with the data obtained. Please note that we make no attempt to validate the contents of fields. Although in real scripts this is a desirable and sometimes necessary action.

    Discussion: Writing to files

    One of the things you can do with the data is to write it to a file. Perl provides a set of functions for opening, processing, and closing files. This way you can create a new HTML document, add data to an existing HTML document, or save the data in a text file for further processing.

    The file open function looks like this:
    open(HANDLE, "name"); # Open file for reading open(HANDLE, ">name"); # Open a file for writing open(HANDLE, ">>name"); # Open file to append to end

    HANDLE is any temporary name that you will use as a file identifier when performing operations. Once the file is open, you can write to it using the print function:
    print HANDLE "This text will be placed in the file as is.\n"; print HANDLE "In this case, the variable ",$variable," will be placed in the text."; print HANDLE "The $variable variable can be placed in text anyway.\n"; print HANDLE "Quotes and other special characters \; need to \"cut\".\n";

    After completing operations with the file, you need to close it:
    close(HANDLE);

    After this, all recorded data will be saved to disk.

    Before writing to a file, you must make sure that the web server has access to the directory in which the file is located and has permission to write to this file.

    Note that the close function should be located as close as possible to the last write function to the file. This is due to the fact that the web server runs in a multi-user environment, and the script can be run simultaneously by several users. When you open a file for writing, it (the file) is locked and other instances of the script will not be able to open it, which will cause a delay in executing the request.

    Example: Creating a new HTML page

    The following example may seem complicated at first, but all it does is write some information to a file.

    Due to the fact that we are creating a web page, the file contains HTML tags along with plain text. Remember that \n simply inserts a newline into the text for easy viewing of the generated file later.

    All input from the form is contained in the $input(field_name) variables. When printing, such variables must be placed in quotes and separated by commas.

    # Define a variable containing the path to the file to be written $newfile = "c:\webserver\htdocs\mynewpage.html"; # Open the file using the identifier USERINFO open (USERINFO, ">$newfile"); # Form the contents print USERINFO " \n \n"; print USERINFO " Registration Information\n\n"; print USERINFO "\n \n

    Registration details:

    "; print USERINFO "\n

    \n"; print USERINFO "Name: ", $input("user_name"),"\n
    "; print USERINFO "Company: ", $input("co_name"),"\n
    "; print USERINFO "Phone: ", $input("phone"),"\n

    \n\n"; print USERINFO "\n\n\n"; # Close the file close (USERINFO);

    Example: Append to end of file

    Writing to an existing file is easy when you want to append new information to the end of the file. For example, to add new user information to the file created above, you will need the following script:

    # Define a variable containing the path to the file to be written $targetfile = "c:\webserver\htdocs\mynewpage.html"; # Open the file using the identifier NEWINFO open (NEWINFO, ">>$targetfile"); # Add new data to the file: print NEWINFO "\n\n"; print NEWINFO "Name: ", $input("user_name"),"\n
    "; print NEWINFO "Company: ", $input("co_name"),"\n
    "; print NEWINFO "Phone: ", $input("phone"),"\n

    \n\n"; close (NEWINFO);

    Example: Adding to the middle of an existing file

    A more difficult task is to insert new data into the middle of the file. Notice that in the first example we inserted a comment line into the file that looked like this:

    This comment will serve as a marker for us where we need to insert new data. This example does not contain an entirely elegant solution, but is easy to implement and understand. It uses a temporary file, although you can do without it:

    # Define a variable containing the path to the original file $origfile = "/pathname/originalfile.htm"; # Define a variable containing the path to the temporary file $newfile = "/pathname/newfile.htm"; open(INFILE, "<$origfile"); open(OUTFILE, ">$newfile"); while ($line = ) ( printf OUTFILE $line; if ($line =~ //i) ( # Add new data to the file: print OUTFILE "\n\n"; print OUTFILE "Name: ", $input("user_name"),"\n
    "; print OUTFILE "Company: ", $input("co_name"),"\n
    "; print OUTFILE "Phone: ", $input("phone"),"\n

    \n\n"; ) ) # Close files close(INFILE); close(OUTFILE); # Delete original file and rename the new one to the original unlink($origfile); rename($newfile, $origfile);

    Example: Sending data by e-mail

    Sometimes you may want the data entered into a form to be sent to an email address.

    To do this, you will need a mail sending program with a command line interface. Under UNIX this could be sendmail or mail. IN in this example The data is sent using the sendmail program. Instead of writing to a file, we use writing to a specially open pipe:

    # Email address $sendto = "webmaster\@telesputnik.ru"; # Open the channel open (MAIL, "| /usr/bin/sendmail $sendto") # Print to the channel in a special format print MAIL "From: Web server\n"; print MAIL "To: $sendto\n"; print MAIL "Subject: Entering new data"; print MAIL "Someone used the form to enter new data"; print MAIL "Here's what he entered:"; print MAIL "Name: ", $input("user_name"),"\n"; print MAIL "Company: ", $input("co_name"),"\n"; print MAIL "Phone: ", $input("phone"),"\n "; # Send a letter by closing the channel close (MAIL);

    Discussion: Creating web pages on the fly

    The last important part of a Perl script is sending the result back to the user. This is achieved by the same print, but without the file or channel identifier. Everything that is printed to standard output forms the current document in the browser window. For example:

    print "Content-Type: text/html\n\n"; print " \n \n Thank you\n"; print " \n

    Thank you for filling out the form

    "; print "We have received your name, place of work and telephone number,"; print " which you see below:
    \n"; print "Name: ", $input("user_name"),"\n
    "; print "Company: ", $input("co_name"),"\n
    "; print "Phone: ", $input("phone"),"\n

    \n\n"; print "\n";

    Pay attention to the first line. This line contains information about the type of data returned. A double transfer of the stock is required in this case. This page will be returned to the user almost immediately after they click the Submit button.

    Please note that this is just one of many examples of what a page can look like on the fly. In principle, you can generate an HTML document of any shape and content.

    1. Using ready-made scripts

    If you already have written CGI scripts, then before copying them to the server, you should do the following actions:

    • Make sure that the scripts indicate the correct path to the interpreter:

    Perl: /usr/bin/perl
    Python: /usr/local/bin/python

    • If your script requires access to a MySQL database, then you must specify access parameters (see article)
    • In chapter Web server management enable the CGI module.

    Now you can copy your scripts to the server.
    Files must be uploaded to a directory yourdomain/cgi. Files from this directory will be available at http://your_domain/cgi-bin/file_name. In order for CGI scripts to be launched from the root directory of the site yourdomain/docs, you need to create a .htaccess file in it with the following content:

    AddHandler cgi-script .cgi .pl .py
    Options+ExecCGI

    Access rights must be set for scripts 755 or -rwxr-xr-x.
    Access rights can be changed using the control panel.

    2. Writing a simple CGI script

    Let's consider writing a simple CGI script in Perl.
    If you are running Windows OS, then to work with script code you need to use a specialized text editor, for example, Notepad++. Standard for Windows program It is better not to use Notepad. To demonstrate how the CGI script works, you need to create two files. The first file is an HTML document with a text input form:





    Example of working with Perl



    Enter your name:



    The second file is a CGI script

    #!/usr/bin/perl
    use CGI;
    print "Content-type: text/html\n\n";
    $my_cgi = new CGI;
    $your_name = $my_cgi->param("name");
    print "Hello $your_name!!!";

    The first file you can place in the directory yourdomain/docs. You should place the second file in the directory yourdomain/cgi. Be sure to check the rights to your CGI script. They must be set to -rwxr-xr-x or 755 .

    3. View installed PERL modules

    To check the installed PERL modules, you must perform the following steps sequentially:

    • and run the command:

    This will create a modules.pl file

    • Now you need to edit it, to do this, click Insert and write the following:

    #!/usr/bin/perl -w

    use ExtUtils::Installed;

    $installed = ExtUtils::Installed->new();
    foreach $module ($installed->modules())(
    printf "Module: %s\t\tVersion: %s\n", $module, $installed->version($module);
    }

    To exit the editor and save the text you just typed, press Esc and then: wq

    • We can see the installed modules:

    perl ./modules.pl

    4. Installing additional PERL modules

    You can install additional PERL modules from source code on your hosting. Before you begin installation, connect latest version PHP in section Web server managementPHP module management hosting control panel, this will connect an updated set of software, which may include the Perl module you need.
    Before installation, you need to set environment variables so that the installed modules are available to the interpreter.

    • To do this, create a .bashrc file in your home directory using the command:

    cat >> ~/.bashrc<< "EOF"
    PERL5LIB=$HOME/PERL/lib:$HOME/PERL/lib/perl5
    export PERL5LIB

    MANPATH=$HOME/PERL/share/man
    export MANPATH
    EOF

    • For the changes to take effect, run the command:

    source ~/.bashrc

    In order to install the selected module for PERL, you must run the following sequence of commands:

    • on the page http://search.cpan.org/ find the required module, for example, Net::SMPP and copy the link to download the archive with the module source codes,
    • connect to your hosting via SSH and go to the directory for temporary files
    • upload the archive to your hosting using the found link using wget

    wget http://search.cpan.org/CPAN/authors/id/S/SA/SAMPO/Net-SMPP-1.12.tar.gz

    • unpack the archive and go to the directory with the module source codes

    tar -xf Net-SMPP-1.12.tar.gz
    cd Net-SMPP-1.12

    Installation must be performed in a separate directory, for example, /home/login/PERL, Where login- hosting service identifier by specifying the INSTALL_BASE variable.

    • Makefile.PL use commands:

    perl Makefile.PL INSTALL_BASE=$HOME/PERL
    make
    make install

    • To install a module using a file Build.PL use commands:

    perl Build.PL
    ./Build --install_base $HOME/PERL
    ./Build install --install_base $HOME/PERL

    To use installed modules in a Perl script, you need to connect them by adding the following lines to the script file:

    use lib "/home/login/PERL/lib";
    use lib "/home/login/PERL/lib/perl5";
    use Net::SMPP;

    In order for the Apache web server to work with additional modules, you need to enable the module in your hosting control panel env_module and add the following lines to the file .htaccess in the root directory of the site or in the directory with CGI scripts:

    SetEnv PERL5LIB /home/login/PERL/lib:/home/login/PERL/lib/perl5

    where login is the hosting service identifier.

    5. Possible errors

    Error 403

    If you see a 403 error message when accessing a script, this means that the script has incorrect access rights. CGI scripts must have the execution attribute set (permission 755 or -rwxr-xr-x). Attributes can be changed using the Control Panel File Manager.

    Error 500

    If, when running your script, you see a message about the 500th error, this means that the script has an error due to which the Perl translator cannot complete its work successfully. The error can be either a syntax error (for example, you forgot somewhere - then close the quote or curly brace), and logical, for example, as a result of some of your actions, division by zero occurs. In order to understand the cause of the error, you need to look at the web server log files, which are stored in the /var directory /log/.

    Data types are used in programs when declaring variables. In short, a data type defines the set of values ​​that a variable can take, as well as the set of operations that a program can perform on it. IN Perl language the data can be a number or a character string.

    One value is called a scalar quantity or simply a scalar. The following are examples of scalar values ​​that are used in Perl:
    - Decimal: 127 or 127.0 or 1.27E2
    - Hexadecimal: Ox7F or 0x7f
    - Octal: 0177 (first 0 indicates octal is used)
    - String: "Hello World\n" or "Hello World"

    For example, the following command uses the Perl debugger to print the octal number 0177, which corresponds to the decimal number 127:

    D.B.<4>r 0177 127

    Perl translates the data into its internal format. When Perl prints octal or hexadecimal values, it first converts them to decimal format, as shown.

    Note: As you will learn, Perl script allows you to use the printf function to print values ​​in a callable format, such as octal or hexadecimal.

    Double precision floating point format is used as the internal representation of all numbers. In other words, there is no integer among the internal formats. However, in most cases you can ignore this and Perl will do everything right. For example, if you use quantities in a context where only integer values ​​make sense, Perl will automatically truncate the number itself.

    Note: If you are programming in C and have used integer division with integer truncation automatically, then when programming in Perl, you must remember to perform the truncation manually using the int() function.

    The following command illustrates how Perl handles integer and floating point numbers:

    Print 6&3; # will print 2 print 6.9 & 3.1 # print 7 / 2 # will print 2.3333 not an integer print int(7/3) # will print 2

    The same way Perl converts floating point numbers to integers: when a script uses integer values, it also converts numbers to strings and vice versa when such a conversion makes sense. For example, if the script uses numbers in a context where only strings make sense, such as when concatenating strings, it converts the numbers to strings. Likewise, if you want to use strings where only numbers make sense, Perl converts them to numbers. When working with Perl scripts, you usually don't have to worry about the internal representation of scalar values.

    Perl also supports the concept of boolean values, but does not have a special type to describe them. As in C, a numerical value is considered true if it is not zero. Additionally, a string value is treated as true if it is not equal to "" or "0". Some Boolean operators such as<>> (greater than), return one as value<истинно>and zero - as<ложно>.

    Thus, your script should simply treat non-zero values ​​of both string and numeric types as boolean values<истинно>. Perl scripts can group scalar values ​​together and create a list. If a script stores a list in some variable, then this variable becomes an array.

    VARIABLES

    Perl supports three types of variables: scalars, arrays, and associative arrays. As in C, variable names are written with a distinction between lowercase and uppercase letters. Thus, the names VAR, Var and var describe different variables. A script can have a scalar variable called var and an array variable also named var. They will differ in Perl according to the context.

    Note: Perl variables are untyped, as they are in C. For example, a scalar variable can contain any type of scalar, and type casting is automatic. Also, as you may have already noticed, variables in Perl do not necessarily have to be declared. If a variable is not declared, Perl treats it as global. Below you will learn about the declaration of variables and their scope.

    SCALAR VARIABLES

    As noted, a scalar variable can contain a single value. In Perl, scalar variable names always begin with a ($). The following expression assigns the scalar variable $age the value 35 and the variable $name the string value . The print function is then used to print the value of each variable:

    $age = 35; $name = "Bob"; print ($name,"is",$age);

    If you save these expressions in a file called SCALAR.PL, you can run the program like this:

    C:\PERL> Perl SCALAR.PL Bob is 35

    ARRAYS

    As mentioned above, arrays are variables that take a list of scalar values ​​as a value. The following Perl program text illustrates the declaration of array variables and their initialization:

    @days = ("Sun","Mon","Tue","Wed","Thu","Fri","Sat"); print(@days); # will print "SunMonTueWedThuFriSat" print($days); # will print "Thu" @weekdays = @days; # value ("Mon","Tue","Wed","Thu","Fri") @emptylist = (); # wait list

    Reference to type variables<массив>usually begins with an (@) sign and is followed by values ​​in square brackets (). As in C programming, array indices for scripts are always integer type variables, which usually start with a null value. You'll see exceptions to these two rules in the examples that will be explained in this chapter. The third expression ($days) is an example of an array that references a scalar value. Since it contains only one element, the resulting value is a scalar.

    If you use the ($) sign instead of the (@) sign, the script will refer to a scalar value. This note is very important. Square brackets indicate that the script is referencing an array. The $ sign, in turn, indicates a reference to a scalar value. Initializing the @weekdays array is done by selecting part of the @days array. In the previous example, the @days array was used without an index. When the index is omitted, Perl refers to the entire array. Similarly, in the previous example, the @days array was initialized with a list of literals.

    In addition to assigning literals as values ​​to an array, the script can also assign the values ​​of variables or even other arrays to arrays, as shown below:

    @stuff = ($age, $name) @FriendsOfMine = ("Joe","Mary", @FriendsOfYours);

    The following example uses parts of arrays:

    @weekend = @days ; # result ("Sun","Sat") print (@days); # will output "MonTueWedThuFriSunSat"

    If a script uses an array variable in the context of a scalar, then the value is the number of array elements. A scalar context is one where only scalar values ​​are meaningful. For example, the following expression uses the scalar context for the stuff array to determine the number of elements contained in the array. If the number of elements is greater than or equal to 2, then the script displays a message and ends execution:

    (@stuff >= 2) || die "Too much stuff!\n";

    The die function directs Perl to terminate execution and issue a specified message. If the message is not contained, then the function simply ends the script.

    Perl also supports a special $# variable construct that returns the last index value in an array. For example, the following for expression uses $[ to determine the starting index value of an array, and $# to determine the last element of the array. In this case, using the for expression, the values ​​of each of the elements are displayed:

    For ($i =$[; $i<= $#stuff; $i++) { print $stuff[$i]; }

    Recorded for loop can be replaced by the following equivalent expression:

    Print @stuff;

    ROLE OF CONTEXT FOR SCALAR AND VECTOR TYPE VARIABLES

    Note that the list construction operator (,) looks exactly the same as the sequentialevaluation operator (,). Which operator is used depends on the context in which it appears, in particular whether the variable is a scalar or an array. Perl uses list construction in the context of arrays and sequential evaluation for scalars. Consider the following expressions:

    @an_array = (1,2,3,4,5); $a_scalar = (1,2,3,4,5);

    The first expression initializes the array, while the second expression sets the scalar variable $a_scalar to 5, discarding the first four values. Consider the following two expressions:

    Print $assoc(1,2); print @assoc(1,2);

    The first case will print one value of an associative array with two keys, while the second will print two values ​​of an associative array with one key. Of the following two expressions, the first copies a list, while the second assigns a scalar value equal to the size of the array:

    @x = @list; $x = @list;

    ASSOCIATIVE ARRAYS

    Associative arrays are similar to regular arrays in that they are a list of scalar variables. The difference is that an array must use integer values ​​as indices when selecting array elements, whereas an associative array can use values ​​of any type to select array elements. The index values ​​for an associative array are called keys. Consider the following examples:

    $ages("Bob") = 35; $ages("Mary") = 25; $, = " "; # change output separator for print operator print @ages("Bob","Mary"); # will print "25 35" print keys(%ages); # will print "Bob Mary" for $name (keys(%ages)) ( print "$name is $ages($keys)\n"; )

    As you can see, the program assigns values ​​to the variable "$," (a scalar variable whose name is a comma). The script uses this expression so that when the print statement is used later, the output data does not merge with each other. Special variables such as "$," are discussed later in this chapter. Associative arrays are identified using curly braces. As with arrays, indexes are not used when referencing an entire associative array. For example, link@ages("Bob", "Mary") uses indexes in parentheses, which points to an associative array. The @ prefix indicates that we are talking about an array. Similarly, using a dollar sign in front of an array indicates that a scalar quantity is being used.

    Note: If two keys are specified, then together with the @ sign this indicates that we are talking about part of an associative array and the result should be in the form of a list. This expression is equivalent to #ages(" Bob"), #ages("Mary"). which has the value (35, 25).

    The print keys(%ages) expression calls the keys operator, which returns the complete list of keys in the associative array. A %ages reference with a percent sign as a prefix means that the reference refers to the entire associative array. Note that the for loop refers to variables enclosed in double quotes. Finally, the last example discussed also uses the keys operator and introduces a for loop to print out all the combinations of the associative array. The for loop refers to variables enclosed in double quotes. Perl, in turn, will replace the values ​​referenced by the variables while it parses the string. Programmers call this process variable substitution or interpolation.

    Note: Perl does not interpret variables containing single-quoted strings.

    PERL OPERATORS

    While Perl's data and variable types are quite different from those of C, Perl's operators and expressions should feel much more familiar. All C operators are present in Perl except the type operator, the *ptr contents operator, and the var.member or var->member operator. In addition, Perl introduces many new operators for use in operations such as string comparison and string manipulation.

    ARITHMETIC OPERATORS

    Arithmetic operators operate on numeric values ​​and their result is a number. If an expression includes string operands, Perl converts the string values ​​to numeric values ​​before evaluating the expression. Perl converts strings to numbers in a similar way to the C atof() function in the runtime libraries. Perl currently supports the following arithmetic operators:
    - + addition
    - - subtraction or change of sign
    - * multiplication
    - / division (for floating point numbers only)
    - % modulo (only for integer values)

    Let's look at examples of the following arithmetic operations in Perl:

    $x = 2.5; $y = 3; print ($x + 2*$y); # will print 8.5 print (7 / $y); # will print 2.3333333 print int (7 / $y); # will print 2 print (7 % $y); # will print 1 print (7.5 % $y); # will print 1

    Note: In Perl, the division operator always results in a floating-point number, and the result of taking one number modulo another is an integer, and both operands are first converted to an integer type.

    Consider the following modulo operation:

    Print (7.9% 3.6); # will output 1 same (7% 3) = 1

    Perl also supports increment and decrement operators:
    - ++ decrement in prefix or postfix form
    - - increment in prefix or postfix form. Let's look at examples of increment and decrement operations:

    $x = 4; +$x; print $x; # will print 5 $y = $x-; # will decrement x after assigning y the value of x print "$y $x" # print 5 4

    Finally, Perl provides an arithmetic operator for exponentiation (**). Consider the following examples of using the exponentiation operation:

    $x = 2 ** 3; # result 8 $x = 2 ** 0.5; # square root of 2 $x = -2 ** -3; # 1/(-2 cubed), result -1/8 (-0.125)

    BITCH OPERATORS

    Bitwise operators operate on the binary representation of integers and have an integer result. If the operand is a string or a fraction, Perl first converts it to an integer and processes the operand using the 32-bit representation. All C bitwise operators are represented in Perl:
    - | bitwise OR
    - & bitwise AND
    - ^ bitwise exclusive OR
    - ~ bit inversion
    - << сдвиг влево
    - >> shift right

    Consider the following examples of bitwise operations:

    $x = 5; #101 in binary $y = 3; #011 in binary print $x | $y; # 7 (111) print $x & $y; # 1 (001) print $x ^ $y # 6 (110) print $x & ~1; # 4 (100) print $x<< 2 # 20 (10100) print $x >> 1 # 2 (10)

    As in C, the behavior of right shift operators depends on the language implementation when the operand is negative.

    COMPARISON OPERATORS

    Comparison operators compare the values ​​of two operands. Just like with arithmetic operators, Perl converts string operands to numeric operands before performing the comparison. To allow a script to compare strings that are not numbers, Perl has additional string comparison operators. These operators compare strings using ASCII values. If a numeric value is given as the operand of a string comparison, it is first converted to a string. Table 12.1 lists comparison operators:

    Number String Value = = eq equals!= nе not equal > gt greater than< it меньше чем >= gе greater than or equal to<= lе меньше или равно <=>cmp not equal (signed result)

    Table 12.1. Perl comparison operators.

    The result of a comparison operation is one if the comparison is true and zero otherwise. However, the last operation (<=>or cmp) can return the values ​​-1, 0, or 1 depending on whether the value of the first operand is less than, equal to, or greater than the second.

    Note: Perl's cmp operator behaves similarly to the C runtime library's Strcmp() function.

    Let's consider next example comparisons:

    $x = 5; # x equals 5 print ($x< 4); # если false, то выведет 0

    LOGICAL OPERATORS

    Logical operators parse Boolean expressions and return values<истинно>or<ложно>as a result. Perl treats the operands of logical operations as Boolean values, i.e. as true or false.

    Perl's logical operators include the following:


    - || logical OR
    - && logical AND

    Perl always processes boolean expressions from left to right. Besides. Perl always stops evaluating if the evaluation already performed is sufficient to determine the value of the result. In addition to the general logical operators, Perl supports the following additional logical operators:


    - ! logical negation()
    -
    -: conditional operation
    - , sequential execution

    The logical negation operator (!) replaces the value of a Boolean value with its opposite value. Just like in C, Perl has a conditional operator (
    -:) uses three operands. An expression using a conditional operator has the following form:

    Condition
    - true-result: false-result

    Similarly, the following expression uses a conditional operator to give Bob full access and everyone else limited access:

    $access = ($user eq "Bob"
    - "Full" : "Limited");

    Sequential operator<,>(also known as the comma operator) is not a completely logical operator because it does not examine the truth of its operands. Perl evaluates the operands of the sequential operator from left to right and returns the value of the rightmost operand. The following example illustrates the use of the comma operator in a for loop.

    For ($i=0, $j=10; $i<10; $i++, $j-) { print i$," ",$j }

    STRING OPERATORS

    Since Perl is a text processing language, it is not surprising that it includes additional operators for manipulating strings. The following are the string processing operators:
    -. string concatenation
    - x replication
    - =~ variable pattern matching
    - !~ the same as the previous one, but with the added negation of the result

    The first two statements are easily illustrated with an example:

    Print "b" . "an" x 2 . "a"; # will print "banana"

    As shown, this expression uses string concatenation and the replication operator to print the string .The last two operators are used to test whether a string operand includes a given pattern. This issue is discussed in detail in the section<Регулярные выражения>. The following example illustrates their use:

    $var = "banana"; print ($var =~ /ana/)
    - TRUE: FALSE;

    In this case, the pattern string occurrence test operator (=~) was used to check whether the pattern ana is in the $var variable. IN in this case the expression takes on the value<истинно>.

    ASSIGNMENT OPERATORS

    If you are familiar with the C programming language, then the forms of Perl's assignment operators should be quite familiar to you. Just like in C, these operators force Perl to perform special operations on the values ​​that appear on the right side of the operator and then perform an assignment:

    = += -= *= /= %= |= &= ^= ~= <<= >>= **= .= x=

    LVALUES In Perl, as in C, an lvalue is the name of what appears on the left side of the assignment operator. Thus, an lvalue represents an entity that can be assigned a value, for example, an lvalue can be a variable. For example, a Perl script cannot assign a value to a string of characters, such as the expression = 32 because is not an lvalue. However, the script could assign a value to $Bob, such as $Bob = 32, since $Bob is an lvalue. In Perl, any entity that can be used as an lvalue usually is. For example, the following expression packs and unpacks a list of values, with the list of variables in the first case and three scalars in the second being lvalues:

    @color = ($r, $g, $b); # color pack ($r, $g, $b) = @color; # color unboxing

    When you work with lists in Perl, the assignment operator does not necessarily apply to the entire list. The script can assign values ​​to individual list elements, as shown below:

    @items = (100,200,300);

    In this case, the operator assigns a value to three elements of the list. Similarly, the following expression unpacks the elements of a list, assigning the values ​​of the first two elements to two scalar variables, and the remainder of the array to a list variable:

    ($arg1,$arg2,@rest) = @ARGV; # you can mix scalars and arrays

    OPERATIONS FOR WORKING WITH LISTS

    Operations for working with lists include the following:

    List constructor - .. scope operator - x replication operator

    You've already used the list constructor to initialize arrays and create a list of variables used as lvalues. The range operator returns as its value a sequence of integers that starts from the left operand and continues up to and including the right operand. Scripts often use the scope operator in conjunction with a list constructor to create lists. For example, the following expression uses the scope operator to create a list called @digits that contains the numbers zero through nine:

    @digits = 0..9; # list (1,2,3,4,5,6,7,8,9)

    Similarly, this expression can use the scope operator to create a scope of changes to array indices. Suppose the list @days contains the days of the week (starting with Sunday). The following expression assigns the @weekdays list values ​​starting from Monday through Friday:

    @weekend = @days;

    Finally, the following expression uses two area operators to create a list of hexadecimal digits:

    @hex_digits = (0..9,a..f);

    The replication operator simply creates copies of a given operand the specified number of times. For example, the following expression repeats the list of values ​​1, 2, 3 three times:

    OPERATORS FOR WORKING WITH FILES

    Perl contains an extensive list of operators for working with files. There are at least 27 operators that return specific information about a file without even opening it. Many Perl statements are targeted at UNIX systems, but the following statements work on any system:

    D checks for directory presence
    --e determines the presence of a file
    --s specifies file size
    --w determines whether the given file can be written to

    The next two file operators return a boolean value. The third operator returns the file size in bytes. The following text illustrates the use of these operators:

    If (-e,"perl.exe") ( print "File size is:" -s "perl.exe"; ) else ( print "can\" t find perl.exe\n"; ) (-w "SomeFile ") || die "Cannot write to SomeFile\n";

    OPERATOR EXECUTION PRIORITIES

    Like any programming language, Perl determines the execution priorities of operators, with the help of which the sequence of their execution is ordered. Table 12.2 lists the operator priorities from highest to lowest:


    - ++
    - ! ~ unary minus
    - **
    - =~ !~
    - * / % X
    - +
    - <<>>
    - -d -e -s -w (and other file operators)
    - <> <= >= It gt le ge
    - = = != < =>eq ne cmp
    - &
    - |^
    - &&
    - ||
    - ..
    -
    - : = += -= *=

    Table 12.2. Perl operator precedence from highest to lowest

    In your script, you can change the order in which statements are executed using parentheses.

    PERL CONSTRUCTS

    Perl supports all C expressions using an almost identical format. For example, control constructs if, while, do. for and goto are used in the same form in both languages. As you'll see later, the continue statement has a slightly different meaning in Perl. Its former value is now called next, and the break statement is now called last. Perl doesn't implement switch statement. In addition, some C language expressions can be found in Perl in other formats, and many new expressions have been added.

    SIMPLE AND COMPOSITE OPERATORS

    A simple expression is any valid combination of operators and operands. In Perl, an operator is an expression ending with a semicolon. As in the C programming language, all statements end with a semicolon. When you output program text to the debugger, you can omit the semicolon because the debugger will supply it for you. The following text illustrates a simple assignment operator in Perl:

    $Title = "Web Programming"; !}

    Just like C programming, Perl scripts can contain statement blocks, or compound statements, which are placed inside curly braces (()), as shown below:

    (#Operators#Another operator block)

    Your scripts will make extensive use of instruction blocks along with more complex statements. As in C, Perl scripts can use blocks of statements to define the scope of local variables. However, the definition of local variables in a block is not automatic. The script must use the local keyword to declare them. We'll look at the scope of variables in detail later in this chapter.

    CONDITIONAL OPERATORS

    Many of the previous examples used the if statement. In Perl, the if statement is almost identical to the if statement in C. The difference, however, is that in C the if statement can use a simple statement without curly braces, whereas in Perl the statements must be enclosed in braces, forming a block.

    If (expr) statement; // acceptable for C but not for Perl if (expr) ( statement; # this is how you should do it in Perl)

    Similarly, Perl's else statement works slightly differently from the corresponding statement in C. In Perl, statements must also be enclosed in curly braces and form a block:

    // Example in C is not acceptable in Perl if (expr1) statament1; else if (expr2) statement2; else ststement3;

    The following shows that Perl allows you to use the elsif construct:

    If (expr1) ( statament1; ) elsif (expr2) ( statement2; ) else ( ststement3; )

    OPERATOR UNLESS

    In the C programming language, programmers use logical negation (!) to reverse a Boolean value, as shown below:

    If (!(expr)) // Negation in C ( statement; )

    Along with the use of logical negation, Perl scripts often contain an unless statement, which does the same thing as the C code above.

    Unless (expr) ( statement; )

    Note: Unlike C, Perl does not contain a switch statement.

    DO OPERATOR

    One special case of block operators is the do operator, which allows a block of statements to return values. The value that the do statement returns is the value of the last expression evaluated within the block. For example, the following do statement compares the string variable $Month with the months of the year and sets the variable $DayCount to the number of days in the month:

    $DayCount = do ( if ($Month eq "September" || $Month eq "April" || $Month eq "June" || $Month eq "November") ( 30; ) elsif ($Month eq "February" ) ( $Year & 3
    - 28: 29; # Check for leap year ) else ( 31; ) );

    Note that Perl requires a semicolon at the end of the do block. Don't confuse the do block with the do while statement, which will be discussed later in this chapter.

    CYCLES AND BRANCHES

    Perl supports the for, while, and do loop statements with minor differences from their implementation in C. The significant difference is that Perl requires statements to be used in blocks enclosed in curly braces. Also, as you'll see, Perl extends the loop construct to provide some new forms. In the following examples, the for, while, and do loops work similarly in C and Perl:

    For($i = 0; $i< 100;$i++) { printf("%d\n", $i) ; } while ($i >0) ( printf("%d\n", $i-); ) do ( printf("%d\n", $i++); ) while ($i< 0);

    The design of loops in C is different from that in Perl in that Perl does not contain a break statement, and the continue statement performs a completely different function. Fortunately, Perlo provides some new, more flexible and more intuitive constructs:


    - last exits the loop (like the C break operator)
    - next start a new iteration (like the C continue statement)
    - redo repeat the current iteration

    To understand loop constructs in Perl, you need to understand the use of the continue block. Consider the following while loop, which contains a continue block:

    $i = 100; while ($i > 0) ( print $i; ) continue ($i-)

    You can think of a continue block as the third expression in a for loop that is executed every iteration. Similarly, Perl executes a continue block at the end of each iteration. However, as you will learn later, the continue block provides the script with more full control over the process, which is what the for loop provides. When a Perl loop uses the next statement, the continue block is still executed if it exists. However, if the loop uses a redo statement, the continue block is not executed.

    TAGS

    In a Perl script, labels simply mean a name corresponding to some position within the script. Label names end with a colon (for example, outerloop:). Using the goto statement, the script can jump to a label. Additionally, the last, next, and redo operators can be used to jump to a label. The following code illustrates the use of the last operator to jump to a label:

    Outerloop: while ($i > 0) ( while ($j > 0) ( #Some other process here if ($needToAboutLoop) ( last outerloop; ) ) )

    In this case, the instruction contains a last branch to jump to the outerloop and end the loop.

    UNTIL LOOP

    Another loop construct in Perl is the until loop, which is the opposite of the while loop. Remember, in a while loop, statements are executed as long as the specified condition is met. In an until loop, on the other hand, instructions are executed until a condition is met. For example, consider a while loop such as the one shown on the next page.

    While (!(expr)) ( statement; )

    Using an until loop, you can create an identical loop shown below:

    Until (expr) ( statement; )

    Similarly, the following do while statement uses the logical negation operator to loop until a given Boolean expression evaluates to true:

    Do ( statement; ) while (!(expr));

    Using the do until construct, you can form an identical loop without using logical negation:

    Do ( statement; ) until (expr);

    FOR AND FOREACH CYCLES

    Perl supports for loops in a very similar way to C:

    For (statement1; expression; statement2) ( statement3; )

    For example, the following code uses a for loop to print the values ​​of numbers from 0 to 100:

    For ($digit = 0; $digit<=100; $digit++) { print $digit, " "; }

    Additionally, Perl includes a foreach loop construct that allows a script to iterate over lists and arrays. Let's look at an example:

    @list = ("a","b","c"); foreach $arg (@list) ( print "List item: $arg\n"; ) foreach $i (1..10) ( print "iteration $i\n" )

    In the first case, the foreach loop iterated through the values ​​of the @list variable. In the second example, the foreach loop iterates over numbers in the range from 1 to 10. The foreach loop can contain a list of literals or an array, as illustrated in the previous example. After one iteration of the loop, a special scalar variable ($arg in the first case and $i in the second case) takes a value from the given list of elements. The scope of this scalar variable in a foreach loop is limited to the body of the loop. Therefore, a scalar loop variable, foreach, will not conflict with an identical variable name defined outside the loop. The following code uses a variable named $i inside and outside a foreach loop:

    $i = 1001; foreach $i (1..9) ( print "$i\n"; # loop will print 123456789 ) print "$i\n";

    As you can see from this example, the $i variable used to organize the loop iterations does not conflict with the $i variable defined outside the loop. A feature of the foreach loop that your scripts can take advantage of is the ability to modify array elements. (Be careful when implementing this feature!) Consider the following foreach loop, which adds the value 10 to each array element:

    @list = 1..5; foreach $i (@list) ( $i += 10; ) $, = " "; print @list; # will output 11 12 13 14 15

    Let's make a few final notes about the foreach loop. Perl treats the names foreach and for as synonyms. Therefore, you can use these names interchangeably in scripts. Perl, in turn, will determine the type of loop based on its context.

    UNCONDITIONAL JOB OPERATOR GOTO

    Perl supports the goto operator, which is identical to the C programming language operator. Below is an example of using the goto operator to print numbers from 1 to 10:

    $i = 1; loop: print $i++, " "; if ($i<=10) { goto loop; }

    OPERATOR MODIFIERS

    Perl uses special forms of the if, unless, while, and until constructs to control the progress of calculations. In certain cases, these special constructs can make your code clearer and easier to read. To make the code easier to read and its meaning more obvious, it is advisable to choose a suitable format for recording. Consider a watch expression that uses the die function to terminate the script if the value of the $count variable is less than 10:

    If ($count< 10) { die; }

    By placing the die function before the if statement, as shown below, the number of lines of code will be reduced:

    Die if ($count< 10);

    Similarly, the same expression can be written as follows:

    ($count >= 10) || die;

    In this case, if the $count variable is greater than or equal to 10, Perl stops further evaluation on that line and the die function is not executed. Otherwise, if the $count variable is less than 10, after evaluating the first part of the expression, the code runs the die function and thereby ends the execution of the script . Finally, in the following example, using the unless construct also reduces the number of lines to one:

    Die unless ($count >= 10);

    Likewise, the following while loops are identical:

    $i = 0; while ($i< 10) { $i++; } $i = 0; $i++ while ($i < 10);

    As you can see, using a modification of the design, the script allows you to reduce the number of lines in the loop entry to one. Likewise, the following until loops are equivalent:

    $i = 10; until ($i >= 10) ( $i++; ); $i = 10; $i++ until ($i >=10);

    Note: In all four cases, even if the expression to evaluate comes after the statement to be executed, Perl first evaluates the condition and only then executes the statement.

    GENERATING DYNAMIC EXPRESSIONS USING THE EVAL FUNCTION

    Because Perl is an interpreted language, your scripts can use Perl to generate code<налету>, that is, dynamically, during script execution. This is exactly how the Perl debugger (which itself is a Perl program named Perldb.PL) works. When designing scripts, you can use such dynamic code to create dynamic variables or even build special routines. Perl evaluates dynamic expressions using the eval function. The following example creates dynamic instruction by assigning the variable as a value text, which, in fact, contains the required Perl language instruction. Further instructions use the eval function to execute this instruction:

    $perl_statement = "print "Hello, world\n";"; eval $perl_statement; # will print Hello, world $i = 1001; $varname = "$i"; print eval $varname; # will print the value of $i

    Note: There are dangers in using the eval function in a script, especially if the script passes user-supplied data to the eval function. Using the eval function, a script can execute an arbitrary Perl command, including even system commands. This gives the user control over the program, which can be especially risky on the Internet and Web.

    SUBROUTINES

    Like all structured programming languages, Perl supports routines. A subroutine can be defined using keyword sub as below:

    Sub demo_sub ( print "demo_sub called\n"; ) &demo_sub; # subroutine call

    In this case, the instructions form a subroutine called demo_sub. To call a subroutine, the script places an ampersand (&) in front of the subroutine name. When calling a subroutine in Perl, the parentheses can be omitted. You can place a routine anywhere within a script's source code because Perl will parse all the source code before executing the script. You can declare a subroutine in the source code immediately after the first use of the subroutine (forward reference). Subroutines can have arguments and return values. The following code snippet contains a routine called show_value that prints the value received by the routine as a parameter:

    Sub show_value ( print "The value id ", $_; ) &show_value(1001);

    Formally, a Perl routine does not declare variables to store arguments. Instead, an array variable named @_ is passed to the routine, which contains the parameter values. In turn, the routine accesses the values ​​of the arguments using the following notation for array elements: $_, $_, etc. However, this method of passing parameters can impair the readability of the code, and therefore most routines use copying of arguments to local variables. Similar to the previous example, the following show_fwo_values ​​routine displays the values ​​of two parameters:

    Sub show_two_values ​​( print "First parameter ", $_, "\n"; print "Second parameter ", $_, "\n"; ) &show_two_values(1001, 2002);

    Finally, the next function, show_all_values, prints the values ​​of all the parameters it receives. The function uses an array to define a number as a parameter:

    Sub show_all_values ​​( for ($i = 0; $i< @_; $i++) { print "Parametr ", $i, " is ", $_[$i], "\n"; } } & show_all_values(1001,2002,3003,4004);

    As stated, Perl routines can return values. The return statement is used for this. Unlike the C language, Perl does not require the use of a return statement. If the routine does not contain a return statement, then the last evaluated expression will be taken as the return value. The following example adds two parameters and returns the result:

    Sub add_values ​​( return $_ + $_; ) print "The result is: ", &add_values(1001,2002);

    LIBRARY OF SUBROUTINES

    Unlike C, Perl doesn't actually support the concept of a library. However, it does have a mechanism that allows scripts to use source code from another file. For example, suppose you store the add_valuesl routine in a file called addvalue.pl. Using the require statement, another Perl script can access that routine, as shown below:

    Require "addvalue.pl"; print &add_values(10,11);

    You can think of the require statement as analogous to the C preprocessor's #include statement. To find a source file, Perl first looks in the default directory for the Perl library (see the installation instructions for details), and then in the current directory. You can also use an absolute or relative path appended with the file name. Perl remembers which files were requested by the require statement and loads them only once, even if those files are accessed multiple times. There are many standard libraries that extend the capabilities of the Perl language. Now is a good time to wander through the directory where the Perl library files are stored to get an idea of ​​the capabilities they offer.

    USING PACKAGES TO ISOLATE SUBROUTINES

    If you have many routines, especially routines that you store in different files, variable name collisions can occur when the same variable name is used for different purposes. Perl helps avoid this with packages. As you know, by declaring local variables for subroutines, you can avoid name collisions. However, if multiple routines share specific data, that data may require a global scope, which can lead to name collisions. Using packages, you can group global data into private name-spaces, outside of the whose global variables are not visible, i.e. unknown. Consider the simple example below, in which two routines (located in different files) use private, individual namespaces.

    # Code in file one.pl sub sub_one ( package demo_one; $some_data = 10; ) # * * * * * * * * # Code in file two.pl sub sub_one ( package demo_two; $some_data = 20; )

    As you can see, the first routine uses the package name demo_one, the second routine uses the package name demo_two. Both routines can set and use the $some_data variable without causing a name collision between one global variable and the other. Script<знает>the name of the package within which the variable resides and organizes access to it, uses the package name as a prefix to the variable name. The following example adds the package name package_one or package_two as a prefix to the variable name some_data:

    &sub_one; &sub_two; print "Variable 1 $package_one"some_data\n" print "Variable 2 $package_two"some_data\n"

    When you use Perl packages, you can create a unique namespace within the current source file by placing a package statement at the beginning of the file, as shown below:

    Package some_package_name $some_data = 1; sub some_sub ( return $some_data; )

    In this case, the $some_data variable exists only in the package and is therefore protected from incorrect access. Using a package thus gives the data the same scope as in the C programming language, where global variables have their scope in the source code file in which they are declared. When calling a routine from another script file, you must use the package name:

    Require "some_package.pl"; print &some_package_name"some_sub;

    ROW PROCESSING

    In the previous examples, you learned how to construct string literals using variable interpolation. You also learned how to concatenate string literals and string variables. In this section, you see that Perl provides a large set of functions that scripts can use to manipulate strings.

    CHOP FUNCTION

    The chop function removes the last character of a string. It has the following format:

    $character = chop(Str);

    The chop function returns the removed character. Perl scripts make extensive use of chop to remove newline and end-of-line characters.

    INDEX FUNCTION

    The index function searches for a given substring in a string. It has the following format:

    $location = index(Str, SubStr[, Offset]);

    The index function returns the index of the first occurrence of a substring (SubStr) in a string (Str). An Offset may optionally be specified after which the search begins. If the substring is found, the value -1 is returned. In the following example, the index function searches for occurrences of the substring "na" after the third character in the string "banana":

    Print index("banana","na",3); # Prints 4.

    RINDEX FUNCTION

    The rindex function looks for the last, rightmost occurrence of a substring in a string and returns the position value of the first character of the substring. The function has the following format:

    $location = rindex(Str, SubStr);

    This function is similar to the index function, except that it returns the last occurrence rather than the first. For example, the following example uses the rindex function to determine the last occurrence of the substring "na" in the string "banana":

    Print rindex("banana","na"); # Prints 4

    LENGTH FUNCTION

    The length function returns the number of characters in a string. It has the following format:

    $len = length(Str);

    The following example uses the length function to print the number of characters in a string:

    Print length("banana"); # Prints 6

    SUBSTR FUNCTION

    The substr function is used to remove part of a string. It has the following format:

    $substring = substr(Str, Offset[,Len]);

    The function returns a substring, that is, a part of a string whose length does not exceed the value specified by the optional Len parameter. The returned substring of str begins at the character at the position specified by Offset. If the Len parameter is omitted, then the returned string contains characters up to and including the end of the line. If the Offset parameter is negative, then the offset is calculated from the end of the line. Finally, the script can use substr as an lvalue to perform an assignment operation. The following code snippet illustrates the use of the substr function.

    Print substr("orange",3); #Outputs "nge" print substr("orange",-2); # Prints "ge" print substr("orange",2,2); # Prints "an" $str = "apple"; substr($str,-3) = "ricot"; print $str; # Prints "apricot"

    Note: Using Perl regular expression operators is often more efficient than using substr functions. Regular expressions are discussed later in this chapter.

    JOIN FUNCTION

    The join function joins a list of elements into a string, separating each element with a given character. It has the following format:

    $new_string = join(Str,List);

    The join function converts each element of a list into a string and joins the strings. The following code snippet illustrates the use of the join function:

    $str = join(",", 0..4,10,20); # The list will be "0,1,2,3,4,10,20" $strn = join ("\t", $a, $b, $c);# Mixes the lists

    SPLIT FUNCTION

    The split function splits the contents of a string into a list of elements. It has the following format:

    Split(Delimeter, Str[,Limit]);

    The Delimeter argument specifies the character by which to split, such as space, word, tab, etc. e. The optional Limit parameter specifies the maximum number of elements the list can contain. The following example illustrates the use of the split function.

    FUNCTIONS FOR PROCESSING LISTS

    In the examples discussed earlier in this chapter, we learned how to create a list, store it as the value of a variable, iterate through all the elements of the list, and access an individual element of the list. In this section, you'll learn a few more features that expand your list-working capabilities.

    REVERSE FUNCTION

    The reverse function reverses the elements of a list. It has the following format:

    @new_list = reverse(@List);

    The reverse function reverses a list and returns a new resulting list. The following example illustrates the use of the reverse function:

    @list = reverse(1..5); # Result 5,4,3,2,1 @list = reverse(@list); # Result 1,2,3,4,5

    SORT FUNCTION

    The sort function sorts the elements of a list. It has the following format:

    @new_list = sort(@List);

    @new_list = sort(Subroutine @List);

    @new_list = sort(BlockStatement @List);

    The sort function places elements in a list, ordering them according to the ordinal character numbers in the ASCII table. Like the reverse function, the sort function returns a new list as its value and does not affect the original list. The following example illustrates the use of the sort function:

    @list = sort(1,5,2,3,4); # Result 1,2,3,4,5 @list = sort(1,2,10); # 1,10,2 sorting in ASCII

    In a subroutine or block, you can change the order in which the sort is performed. The following example illustrates the use of the sort function.

    @list = sort(($a<=>$b) (2,1,10)); # @list 1,2,10 @list = sort(($b<=>$a)) (2,1,10); # @list 10,2,1 sub mycomp ( $b<=>$a ) @list = sort(mycomp (2,1,10)); # @list 10,2,1

    FUNCTIONS FOR WORKING WITH ARRAYS

    As you know, an array is a data structure containing one or more values ​​of the same type, for example, 100 student names. Perl contains several built-in functions that help you work with array elements. The following sections cover several basic array processing functions.

    PUSH AND POP FUNCTIONS

    Perl scripts use push and pop fictions to add and remove elements from the end of an array. In other words, the push and pop functions allow scripts to perform stacked operations on a last-in, first-out basis. The push function has the following format:

    Push(@ARRAY, LIST);

    The following snippet illustrates the use of the push function:

    @list = (); push(@list,10,20); # @list is now (10,20) push(@list,1..3); # @list is now (10,20,1,2,3)

    In contrast, the pop function removes the element that was last pushed onto the stack and returns the value of that element. The pop function has the following format:

    $value = pop(@ARRAY);

    The following program fragment illustrates the use of the pop function:

    # Let's take @list from the previous example print pop(@list); # Print 3 print pop(@list); # Prints 2 # Now @list (10,20)

    SHIFT FUNCTION

    The shift function removes and returns an element from the beginning of an array. This function is similar to the pop function with the only difference that it works from the beginning of the array according to the FIFO principle (<первым вошел, первым вышел>). The shift function has the following format:

    $value = shift(@ARRAY);

    The following program fragment illustrates the use shift functions:

    # Let's take @list from the previous example

    Print shift(@list); # Print 10 print shift(@list); # Prints 20 # Now @list()

    UNSHIFT FUNCTION

    The unshift function adds one or more elements to the beginning of an array. It has the following code:

    Unshift(@Array, List);

    The following program fragment illustrates the use of the unshift function:

    # @list = () unshift(@list,5,10,20); # @list (5,10,20) unshift(@list, 1..3); # @list (1,2,3,5,10,20)

    SPLICE FUNCTION

    Perl scripts use the splice function to remove elements from a list, replacing them with elements of another list. It has the following format:

    Splice(@Array, Offset[, Count[, List]]);

    The splice function removes the specified number of elements (Count) from an array (@Array), starting with the element pointed to by the offset value (Offset), and replaces the elements with elements of another list (List). If the function call does not specify a Count parameter, the function retrieves elements up to the very end of the array. If the function call does not specify a list whose elements replace the original elements, then the function does not add any elements to the original list. The following expression illustrates the use of the splice function:

    @list = 1..10; splice(@list,1,8,5,6); # @list = (1,5,6,10)

    SCALAR FUNCTION

    The scalar function determines the number of elements in a list. It has the following format:

    Rsult = scalar(List);

    Typically, Perl scripts do not need to use the scalar function with arrays, because when a script accesses an array by writing it in a scalar context, it returns the number of array elements. However, scripts can use the scalar function in cases where the context is ambiguous or if the list is not an array. The following expression illustrates the use of the scalar function.

    @list = 1..10; print scalar(@list); # Prints the size of @list

    GREP FUNCTION

    The grep function filters list elements for which a given expression evaluates to<ложно>. It has the following format:

    @list = grep(Expression, List);

    The grep function iterates through the elements of a list, substituting them as arguments into a given expression. The grep function assigns the current expression of a list item to the variable $_ and evaluates the given expression. If the resulting expression is true, then the grep function adds that element to the resulting list. The following program fragment illustrates the use of the grep function:

    @list = grep($_ & 1, 1..10); # @list (1,3,5,7,9) @list = ("a", "" "b"); # @list("a"," ","b") @list = grep($_ eq "", @list); # @list("a","b")

    Note: If expression, modifies a variable. $_, then the original list will also be modified.

    FUNCTIONS FOR PROCESSING ASSOCIATIVE ARRAYS

    As is known, associative arrays are those arrays in which the index is not a numerical value, but, for example, a name. Perl has several built-in functions that make it easier for scripts to handle associative arrays.

    KEYS FUNCTION

    The keys function returns the key values ​​that correspond to an associative array. It has the following format:

    @key_list = keys(%Array);

    The keys function returns an array of keys as a regular list. The following program fragment illustrates the use of the keys function:

    $ages("Bob") = 25; $ages("Mary") = 30; $ages("Zack") = 15; @list = keys(%ages); # @list will be "Zack", "Bob", "Mary" @list = sort keys %ages # @ list "Bob", "Mary", "Zack" for $key (sort keys %ages) ( print "$key is $ages($key)\n" )

    VALUES FUNCTION

    The values ​​function returns a regular array consisting of the values ​​of an associative array. It has the following format:

    @value_list = values(%Array)

    The values ​​function returns an array of associative array values ​​as a regular list. The following program fragment illustrates the use of the values ​​function:

    # Use the values ​​from the previous example %ages = ("Bob", 25, "Mary", 30, "Zack", 15); @list = sort values ​​%ages; # @list (15, 25, 30) @list = %ages; # @list("Zack", 15, "Bob", 25, "Mary", 30)

    EACH FUNCTION

    The each function iterates through the elements in an associative array. It has the following format:

    @key_values ​​= each(%Array);

    Whenever the script calls the each function, it returns a list of two components that contain a key-value pair. When the function reaches the end of the list it returns empty list. The next time the function is called, the iteration process will start over. The following program fragment illustrates the use of the each function:

    # Use the values ​​from the previous example %ages = ("Bob", 25, "Mary", 30, "Zack", 15); while (($name, $age) = each %ages) ( # Print ages print "$key is $ages($key)\n"; )

    DELETE FUNCTION

    The delete function removes elements of an associative array. It has the following format:

    Delete $Array(Key)

    The following statement uses the delete function to remove the element corresponding to the key Bob from the $Employees associative array:

    Delete $Employees("Bob")

    COMMAND LINE ARGUMENTS

    Perl scripts can easily access command line arguments. Whenever a script is run, Perl places the script's command line arguments in the @ARGV list variable. The following program fragment is used to print command line arguments to the display:

    While ($arg = shift @ARGV) ( print "$arg\n"; )

    ACCESS TO ENVIRONMENT VARIABLES

    Accessing environment variables in Perl scripts is also very easy. Whenever a script is run, Perl places copies of the environment variables in an associative array called %ENV. The following statement uses the %ENV array to display the current directory:

    Print "$ENV(PATH)\n"; # Print the current directory

    In addition to retrieving values ​​from the %ENV array, scripts can also modify array elements. Such changes to the %ENV array will change the environment variable setting for any child process created by the script. For example, the following statement uses the %ENV array to change the current path:

    $ENV(PATH) = "c:\\myexec;".$ENV(PATH);

    Note: Changes the script makes to the %ENV array will not affect the original environment variables. In other words, after the script finishes running, the system environment variables will not change.

    FILE INPUT AND OUTPUT

    Perl was specifically designed to be an adequate tool for reading and writing text files. However, as you'll learn later, Perl does perform random access and binary file I/O functions. File operations require a file handle, which is a variable corresponding to a specific file. By default, every Perl script has three standard pointers that Perl automatically opens when the script runs: STDIN, STDOUT, STDERR. These three standard pointers correspond to the standard streams STDIN, STDOUT, STDERR of the C programming language. In addition, the Perl script can open additional pointers to other specific files.

    OPENING FILES AND OTHER STREAMS

    In order for a script to use a file, it must call the open function. It looks like this:

    Open(FileHandle[, FileName])

    Unlike the C runtime library open function, Perl's open function does not contain a mode parameter in the function call. Perl determines the mode to open a file based on the file name. Table 12.3 illustrates the relationship between file opening mode and file name.

    Table 12.3. Perl file naming conventions and access modes


    -Note: Pipe flow mode may not exist on all systems.

    If a filename is omitted from the open function call, Perl assumes that the filename is contained in the $FileHandle string variable. When the script has finished using the file, it closes it using the close function as shown below:

    Close(FileHandle);

    A program fragment illustrates the use of the open and close functions:

    Open(InFile, "test.dat") || die; # open for reading # test.dat open(OutFile, ">test.dat") || die; # create test.dat $AuxFile = ">>test.dat"; open(Aux, $AuxFile) || die; # opens for completion # test.dat close(InFile); close(OutFile); close(Aux);

    Note that file pointers do not have the usual single-character prefixes. As you'll learn later, Perl scripts can store pointer names as scalar variable strings and pass the pointer to any function that can process them. Perl performs value conversion if necessary.

    On MS-DOS, Perl supports an additional feature called hinmode that allows file input/output to switch between text and binary modes. In most systems, the distinction between text and binary modes does not matter. However for operating system MS-DOS newline character is a sequence of two characters (CR+LF). Since most programs do not expect to encounter two characters at the end of a line, the I/O system must perform the conversion. In order to use the binmode function, the corresponding pointer must be opened. The binmode function has the following format:

    Binmode(FileHandle);

    LINE-LINE READING AND WRITING DATA

    The simplest way for a script to read a line from a file is to use the operator . In Perl, a file pointer surrounded by triangle brackets becomes the input-symbol. For example, the following program fragment illustrates the use of the input character to read and display the contents of the Test.dat file.

    Open(InFile, "Test.dat") || die; while ($line = ) ( print $line; # Prints a line from a file ) close(InFile);

    When the input character reaches the end of the file, it returns false, which in this case ends the execution of the while loop. There is a special (blank) input character denoted by<>, which has a very specialized but useful application. The first time a script uses a blank input character<>, it parses the command line arguments. If the string @ARGV is empty, then the input character<>reads from STDIN. If instead @ARGV is not empty, then Perl opens the first of the files specified in the @ARGV variable and reads the contents of the file. When Perl finishes processing one file, it moves on to the next. After the script has read all the files, the symbol<>returns false. Perl scripts can also use the input character to read the entire contents of a file into an array so that each line of the file becomes an element of the array. For example, the following statement reads from the STDIN file into the @lines array:

    @lines = ;

    Writing data to a file is also quite simple. In fact, you did this every time you used the print function. The full format of the print function is as follows:

    Print List;

    If the print function does not receive a file pointer as an argument, it sends the output to STDOUT. The following program fragment illustrates the use of the print function to append data to an output file:

    Open(LogFile, ">>logfile.dat") || die; ############## ($m, $d, $y) = (localtime(time)) ; print LogFile "Captain"s log, Stardate ++m$/$d/$y\n"; close(LogFile);

    Note: The file pointer and output list are not separated by a comma.

    READING AND WRITING DATA BLOCKS

    Programmers often treat text files as text streams simply because one character follows another until the end-of-file marker. If the script must work with a file that is block-oriented rather than thread-oriented, then the script can use the sysread and syswrite functions to process fixed blocks of data. The sysread and syswrite functions have the following formats:

    $result = sysread(FileHandle, $Var, Length[, Offset]); $result = syswrite(FileHandle, $Var, Length[, Offset]);

    If a function call specifies an offset from the beginning of the file (Offset), then the functions will search for the location from which they will begin I/O operations. The sysread and syswrite functions both pass data using a scalar string variable. Because functions process fixed blocks of memory, the data may contain binary values, including zeros and end-of-file markers. If the function call specifies an offset from the beginning of the file (Offset), then the function searches for the location in the file from which it begins to perform I/O operations. If you are working with blocks of data, then scripts can also use the following I/O functions:

    $result = seek(FileHandle, Position, Base); $result = tell(FileHandle); $result = eof(FileHandle);

    The seek function works exactly like the C runtime library function fseek. The Position parameter specifies the position relative to the origin, which in turn is specified by the Base parameter as follows:


    - 0 Search from the beginning of files
    - 1 Search from current position
    - 2 Search from the end of the file

    Perl's tell function works exactly like the C runtime library's ftell function. This function returns the current position in the file from which a read or write operation is being performed. Finally, the eof function, like the C language function feof, returns the value<истинно>or<ложино>, which the script can use to determine when the end of the file has been reached.

    BINARY DATA PROCESSING

    Although Perl is focused primarily on text processing, it can also process binary data. Scripts can move binary data in chunks using string variables, and perform byte I/O operations using the sysread and syswrite functions. However, in order to accomplish anything<полезное>with data, the script is forced to convert the data into its own<родные>scalar formats.

    BINARY DATA STORAGE

    When a Perl script reads a block of binary data using the sysread function, it places that binary data in a scalar string variable. Perl does not care whether these are given, whether they contain nulls or non-ASCII values. Within symbolic Perl strings accepts bytes as bytes. Unlike C, Perl does not use null-terminated strings. If the data is ASCII, the script can process it like any text. But if the data is binary, the script must decompress it before Perl can process the data.

    UNPACKING BINARY DATA STRINGS INTO PERL VARIABLES

    In order for the script to gain access to binary data, it must unpack it into its own scalar format. Perl scripts unpack data using the unpack function, which has the following format:

    $result = unpack(Template, Expression);

    Expression is a regular string variable that holds binary data read by the sysread function, but can also be an expression that must be interpreted as a string. Template is a character template string that describes how to interpret the values ​​in the Expression operand. The following program fragment illustrates the use of the unpack function:

    ($r, $g, $b) = unpack("C3", $color);# will unpack into 3 characters
    - @longwords = unpack("L*", $data); # unpacks into a list of long # words @stuff = unpack("S2L", $bin); # will unpack into 2 shorts and long

    Each pattern character can be followed by a number indicating how many times to use that character. If there is an asterisk (*) instead of a number, the operation will be performed on all remaining data in the row. If the number is not supplied, then it is performed once. The script can put any number of pattern characters into the Template string. Table 12.4 lists the characters included in the string parameter Template along with a description of the effect each of them has on the execution of the unpack function.

    Table 12.4. Pattern symbols

    Pattern symbol Description
    a
    A ASCII string without null character
    b Bit string (LSB comes first)
    IN Bit string (most significant bit comes first)
    With Single-byte signed character
    WITH Single-byte unsigned character
    d Floating point, double precision
    f Floating point value, single precision pattern
    h Hexadecimal string (low order digits first)
    N Hexadecimal string (most significant bits first)
    i Signed integer
    I Unsigned integer
    l Signed integer of type long
    L The same, only without the sign
    n Short integer
    N Long integer
    p Pointer to string
    s Signed short integer
    S Unsigned short integer
    u String decoding
    v Short integer
    V Long integer
    x Skip forward one byte
    X Skip back one byte
    @ Go to a specified position in a line

    PACKING DATA INTO BINARY STRINGS

    To output binary data, the script must pack scalar values ​​into binary character strings. To do this, use the pack function, the format of which is given below:

    $result = pack(Template, List);

    The following program fragment illustrates the use of the pack function:

    $color = pack("C3", $r, $g, $b); $data = pack("L*", @longword); $bin = pack("S2L", @stuff);

    The pack function uses the same pattern characters as the unpack function, except for the a characters. A, u, x, x, @.

    WORKING WITH CATALOGS

    Perl not only provides a wide range of functions for processing files, but also some very convenient functions for scanning directories. In the following sections we will look at some of the main functions for working with directories in detail.

    OPENING, READING AND CLOSING DIRECTORIES

    Perl scripts allow you to open and read the contents of files. Similarly, these scripts open directories and read the names of the files they contain. To open a directory, scripts use the opendir function, passing the directory pointer and path to it. For reading file list contained in the directory, the script uses the readdir function. Finally, the closedir function is used to close the directory. The following program fragment illustrates the use of the readdir function to display a list of files in the current directory:

    Opendir(Dir, $INC) || die; while ($file = readdir(Dir)) ( print "$file \n" ) closedir(Dir);

    This snippet uses the $INC variable to access the current directory. By changing $INC to $ARGV, the script displays a list of files contained in the directory you specified on the command line.

    In addition to the directory functions discussed above, Perl offers a set of functions that allow you to position the current index in a directory listing:

    $result = rewinddir(DirHandle); $result = telldir(DirHandle); $result = seekdir(DirHandle, Position);

    FORMATTED OUTPUT

    In this chapter, you learned several ways to format script output using the print function. Similar to C, Perl also supports the printf and sprintf functions. In addition, Perl also supports generating column-based reports using form templates.

    USING THE PRINT FUNCTION

    The scripts in this chapter made extensive use of the print function. In addition, Perl provides special variables that affect the operation of the print function. Table 12.5 briefly characterizes these special variables.

    Table 12.5. Special variables that control the printing function

    To use these special variables, you simply assign them the values ​​you want. For example, the following program fragment uses the $ variable to specify a separator between print elements:

    $, = "*"; @list = 1..10; print @list; # Prints 1*2*3*4*5*6*7*8*9*10

    It turns out that the $ variable actually affects all lines, not just those that are printed. However, most often you will use it to change the value output by the print function.

    FORMATTED DATA OUTPUT BY PRINTF FUNCTION

    Perl has printf and sprintf functions, which are very similar to the corresponding C runtime library functions. They have the following format: $result = printf( Format, List); $result = sprintf(Format, List);

    By default, the printf function sends formatted output to STDIO, and the sprintf function returns a formatted string. In both cases, the string format is almost identical to the C language functions, except that the Perl language functions do not support the length specifier (*). The following program fragment illustrates the use of the printf and sprintf functions.

    $precision = 2; $pi = 3.1415; printf("%.2f\n", $pi); # will print 3.14 printf("%.$(precision)f", $pi); # will output 3.14

    CALLING EXTERNAL PROGRAMS FROM A SCRIPT IN PERL

    In a sense, a replacement for shell scripts, Perl provides support for system interaction, including calling external programs. The following sections discuss several ways to call external programs from Perl scripts. Be aware, however, that by allowing scripts to execute system commands, you are opening up security holes in your host. As a general rule, do not execute external commands from a Perl script. However, if you are forced to do external commands from a script, you can use the built-in functions system, exec or fork for these purposes.

    REGULAR EXPRESSIONS

    Throughout this chapter, you've seen examples of string processing functions. Many of them are based on the concept of regular expressions. As you can see from the following sections, Perl scripts make extensive use of regular expressions for text processing. If regular expressions are new to you, then don't worry. After a short time, after you've gone through a few sections of this chapter, regular expressions will become easy to understand.

    REGULAR EXPRESSIONS OVERVIEW

    Regular expressions are a fancy term that originated in computer science to refer to a pattern of characters. Perl scripts use character patterns simply to parse the input data, breaking it down into pieces. Often a script can parse input based on spaces, commas, tabs, and other delimiters. But when the input data has an arbitrary format, then regular expressions cope best with this task.

    REGULAR EXPRESSION SYNTAX

    To reduce the size of regular expressions, Perl uses special characters. Table 12.6 lists some of the symbols used by Perl scripts in regular expressions X.

    Table 12.6. Symbols used in regular expressions

    Symbol Description
    . Matches any character (except newline)
    (..) Groups a sequence of elements
    + Matches the previous pattern one or more times

    -
    Matches the pattern zero or one times
    * Matches the pattern one or zero times
    [...] Matches a character from a given set
    [^...] Matches a character from the set obtained by negation
    (...|...|...) Matches one of the alternatives
    ^ Matches the beginning of a string
    $ Matches the pattern at the end of the line
    (n,m) Matches the pattern n to m times
    (n) Matches the pattern exactly n times
    (n,) Matches the pattern at least n times
    \n\tetc. Matches newline, tab, etc.
    \b Matches at word boundaries
    \B Matches within word boundaries
    \d Corresponds to the figure
    \D Doesn't match the number
    \s Matches space
    \S Matches not a space
    \w Matches a letter or number
    \W Matches a character that is neither a letter nor a number

    Perl places regular expressions (patterns) in slashes, i.e., in slashes, for example, in the form /pattern/. The following program fragment illustrates Perl regular expressions:

    # the following regular expressions are true if: /ig/ # string contains "ig" /(b|d|f)ig/ # string contains "big", "dig" or "fig" /+/ # string contains a number /*/ # string contains an identifier

    If these expressions don't make sense to you, don't worry. In this chapter, we are going to look at several regular expressions. For now, just remember that Perl puts regular expressions between two forward slashes, as shown above.

    USING REGULAR EXPRESSIONS TO SEARCH KEYWORDS

    Perl scripts use regular expressions to make string comparisons easier. To check whether a string contains a given pattern, the script can use regular expressions like this:

    If ($str =~ /pattern/)

    In this case, regular expressions take the value<истинно>if the pattern is found in string ($str). If the string by contains the pattern, then the expression returns the value<ложно>. For example, the following expression tests whether the string contains the text WebProgramming:

    If ($str =~ /Web Programming/)

    To check for an exact match, the expression must bind the comparison to the beginning and end of the string. For example, the following expression has the value<истинно>, if and only if the $str variable takes one of three values: , ) :

    ($str =~ /^ba(na) (2,4)$/)

    Similarly, the following expression is true if and only if $str contains the word and is not part of another word such as .

    ($str =~ /\bthe\b/)

    USING REGULAR EXPRESSIONS TO ANALYZE INPUT DATA

    As your Perl scripts become more complex, there will be many cases where you want to know more than just checking whether a pattern matches a string or not. For example, you might want a script to extract a specific string value. By using grouping characters () within a regular expression, the script can extract matching values ​​from a string and form a list of them. For example, the following program fragment uses regular expressions to extract months, days, and years from a list:

    $str = "January 1, 1997,"; ($m, $d, $y) = $str =~ /\s*(\S*)\s + (\d+)\D + (\d(4))/;


    - Skip any first special character;
    - write all non-special characters to the $m variable
    - (variable to indicate months);
    - skip special character;
    - place all numbers in the $d variable (variable for recording days);
    - skip all characters that are not numbers;
    - write four digits into the variable $y (variable to indicate years).

    Perl also supports another form of pattern matching, using the (=~) operator, which adds the negation of the result: (!~). This operator is equivalent to the expression!($str=~/pattern/).

    REGULAR EXPRESSIONS FOR SEARCH AND REPLACE STRINGS

    So far, you've used pattern-matching operators. It turns out that Perl supports two other regular expressions that modify the string variable being tested. In the following statement, Perl replaces the part of the string that matches the pattern with the given string:

    $str =~ s/pattern/replacement/;

    For example, the following instruction will replace the word on :

    $str =~ s/\bcolour\b/color/;

    A small modification allows you to replace all words on :

    $str =~ s/\bcolour\b/color/g;

    In this case, the g at the end of the expression tells Perl that global substitution is required.

    By using the i suffix, you can specify that the search is case sensitive. As opposed to simply checking for a pattern, the following expression also performs replacement:

    $str =~ tr/SearchList/ReplacementList/;

    For example, replacing all lowercase characters with the same uppercase characters could be done like this:

    $str =~ tr/a-z/A-Z/; # changes case from lower to upper

    Consider the following example for yourself:

    $letters = "abcde"; print "$letters\n" # Print abcde $letters =~ tr/a-z/A-Z/; print "$letters\n" # Print ABCDE

    SUMMARY

    This chapter provides an introduction to Perl programming. Using the concepts discussed here, you can write complex CGI scripts in Perl. The next chapter will help you gain the skills to create CGI scripts in Perl that you can run on your own server. Before proceeding further, make sure you understand the following key concepts:

    Perl is an interpreted programming language used by programmers to write scripts for the Web and Internet.

    Perl's constructs resemble those of C in many respects, but Perl offers many additional features, especially for handling strings and files that are difficult to find in C.

    Perl is the primary language for writing CGI programs for the Web and Internet, primarily due to its flexibility, compact style, and high security.

    ESSENTIAL WEBSITES FOR INFORMATION ABOUT PERL

    The following Web sites will help you find information about details you are interested in regarding the Pcrl language, its scripts, and specific information about Perl 5 language resources and its libraries. Use these Web sites as a starting point for your search.

    SUMMARY

    In this chapter, you learned how to use Perl to write fairly complex CGI scripts. Using the technology you've become familiar with, you can provide professional-level programming services to your clients who would like their business to be represented on the Web. Chapter 14 introduces you to the Java language. As you will see Java language well suited for creating Web sites containing animation and multimedia. Additionally, Chapter 14 introduces another language for writing JavaScript scripts. However, before moving on to Chapter 14, make sure you understand the following key concepts:
    - Perl is a versatile and flexible programming language that can be used to develop CGI scripts for the Web as well as traditional programs for everyday use.

    • Perl is well suited for word processing, database access, it is portable and provides security when working on networks. All these characteristics are important for Web programming.
    • Perl scripts widely use regular expressions for text processing.
    • Most scripts on the Web are now written in Perl. However, languages ​​such as JavaScript and VBScript may encroach on Perl's monopoly.




    

    2024 gtavrl.ru.