Pearl scripts. Perl scripts. The role of context for variables of scalar and vector types

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 the database MySQL data, then you need to 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 run from root directory 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

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

perl ./modules.pl

4. Installing additional PERL modules

You can install on hosting additional modules PERL from source codes. Before you begin installation, connect latest version PHP in section Web server managementPHP module management hosting control panel, and the updated set will be connected 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 there is an error in the script 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 a quote or a curly brace), and a logical one, 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/.

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 take data from an HTML form or other source and do something with it.

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. The 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 means of adding 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 the 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;<-- ПРОВЕРЬТЕ ЭТО open (NAMEFILE, ">$input($name) = $value; ) # Save the user output in a file $targetfile = "/usr/local/www/htdocs/names.html"; #

>$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<-- ЗАМЕНИТЕ ЭТО print ", чтобы увидеть Ваш ввод.\n";

\nClick "; print "here"; #

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:

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

Content-Type: text/html

Click here to see your entry.

Step 4 - Testing the Script with the Form

  1. If the script works on its own, you can test it with the form:
  2. Make sure the web server is running.
  3. Launch your browser.
  4. Type the URL where your form is located (note that the line must start with http://, not file://.
  5. Enter your name in the form field and click the "Register" button.

You should see a message like this:
Thank you for filling out the form Click here

to see your input.

  1. 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.

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 defines the path to the interpreter program:
#!/usr/local/bin/perl for UNIX
\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#!/usr/local/bin/perl for UNIX
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.

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 elegant solution, but it 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 the files close(INFILE); close(OUTFILE); # Delete the 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 this example, 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, 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.

I was busy, engaged in self-education, because... I felt like I was stuck in the same thing. I expand my horizons, learn new things, strive for something, it’s very interesting and takes a lot of time.

Now to the point.

My operating system is ubuntu ++. I constantly have to sit in the console for work. Very often the task arises of quickly changing something in a file according to a template. Offhand answer = sed. At one time I read about it, but I realized that using perl I can do the same thing. Time passed, I completely forgot sed, but perl also began to be forgotten, and I constantly cannot find an example of one-line scripts.

Now, in order.

Given.
There is a file xx.txt which contains numbers from 1 to 5, each number is a new line.



1
2
3
4
5

I would like to replace all occurrences of line 3 with something of my own, let it be the string “hello”

Solution:

cd@laptop:~/data/tmp$ perl -ig -ne "s/3/hello/;print $_; " xx.xx
cd@laptop:~/data/tmp$ cat xx.xx
1
2
hello
4
5


cd@laptop:~/data/tmp$ perl -ig -pe "s/3/hello/; " xx.xx
cd@laptop:~/data/tmp$ cat xx.xx
1
2
hello
4
5
cd@cd-acer:~/data/tmp$ ls *g
9.jpg xx.xxg

Explanation.

perl allows you to run one-line scripts without creating a script code file.

Example:

cd@laptop:~/data/tmp$ perl -e "print "test\n""
test
cd@laptop:~/data/tmp$

The -e option is responsible for this, followed by the code to be executed.

One-line scripts, after the code, can take a file as a parameter, and you can also force the code specified -e to be executed for each line.

Example:

cd@laptop:~/data/tmp$ perl -ne "print ;" xx.xx
1
2
hello
4
5

Those. in this case, we asked pearl to print the default string, and since If the -n option was specified, then this command was applied to each line of the xx.xx file, i.e. got cat

There is also a -p option, which prints a line after executing the code. Those. It’s logical that the command is like


perl -ne "dosmth; print $_;" file

will be similar

perl -pe "dosmth" file

Well, now concluding. We have achieved that we can perform any operation on each line in a file, and print it to stdout, but the original statement of the problem sounded like replacing lines in a file on the fly. This is exactly what the -i option is for.


perl -i -pe "dosmth" file

will execute the dosmth code for a single line and replace it in the specified file.

the -i option can take an optional parameter, and then the script will make a backup copy of the file before starting work


cd@laptop:~/data/tmp/1$ perl -ibak -ne "print;" 1.txt
cd@laptop:~/data/tmp/1$ ls
1.txt 1.txtbak
cd@laptop:~/data/tmp/1$ cat 1.txt
1
2
3
cdlaptop:~/data/tmp/1$ cat 1.txtbak
1
2
3
cd@laptop:~/data/tmp/1$

Now the solution itself should be clear, and it should also be clear why I gave two options.

A simple problem has appeared: in one of the configs you need to increase one of the values ​​by one, let it be the build number.

Let's take an example of a config file

cd:$cat config
Key1 Value2
build=projectname.005
one more line

Let's say we need to get the same config but with build=projectnam.006


perl -i -pe "s/(projectname\.)(\d+)/sprintf("%s%03d", $1, $2+1)/e" config

Explanations.

I -pe explained above.

What changed? At the end of the regular expression, the e flag was added, which means that the right side of the expression will be executed as perl code and only after execution the result will be substituted.

Of course you could do something like


perl -pe "s/(projectname\.)(\d+)/$1 . ($2+1)/e" config
Key1 Value2
build=projectname.6
one more line

! the -i option was removed, I wanted the file not to change, and the result to be in the output

As you can see, two leading zeros disappear, which is why the sprintf function was used

4 comments:

Anastasia said...

Thank you. Useful :)
If there are no objections, I provided a link to your blog in my http://aal-blog.blogspot.com/2009/10/stroka1-stroka2.html

said...

No problem. Glad at least something was useful.

Anonymous said...

I have a question...
Is it possible to run a script and give it data to process?
For example, I run a script for combining two databases, there is a request for months... then the output is sent to print...
that is, I would like the data to be sent to the script with the launch...
Thank you in advance

CGI scripts can be considered the most difficult to debug applications. As a rule, they are debugged on the server where they will work. At the same time, the process of finding errors, such as syntax errors, becomes a very difficult task, because Due to the specifics of the CGI interface, error messages at the compilation stage do not “reach” the operator who debugs the script while on the client machine.

And with time-based payments for the Internet, debugging CGI scripts also becomes quite an expensive task :).

The purpose of this article is to present some methods and techniques designed, in the author's opinion, to significantly simplify the process of debugging CGI scripts in Perl, as well as to point out some of the most common mistakes when writing them.

Preparing the working environment.

To write and debug CGI scripts in Perl, it is convenient to use a local Web server, i.e. Web server installed on your computer. Moreover, from the browser’s point of view, working with such a server will be no different from working with a server on the Internet. Almost any Windows web server can be used as a local web server; it just needs to support running CGI scripts.

The simplest options include PWS (Personal Web Server) from Windows9x or IIS (Internet Information Server) from NT. However, if your site uses things like SSI, then it is better to install Apache for Windows. Most of today's hosting providers have Apache Web Server running UNIX, so such compatibility will not hurt. In addition, Apache allows the use of additional non-standard CGI environment variables, so CGI scripts that will "really" run on Apache are better debugged on it (though this is my opinion).

The local server has a "domain name" of localhost and an IP address of 127.0.0.1. Accordingly, it is accessed via a URL like:

Http://localhost/ ...

However, to execute CGI scripts in Perl, installing a Web server is not enough; you also need to install Perl itself. I would recommend Perl for Win32 from ActiveState. After installing Perl, it needs to be “registered” in the Web server settings so that it is a Script Handler for Perl scripts. Different Web servers do this differently, read the documentation for your server. For PWS and IIS, installing Perl is a special task. In most web servers for Windows, the belonging of a CGI script to a certain “type” (Perl script, some other script...), and, accordingly, the handler is determined by the file name extension. If this is the case on your server, you need to install the extension for CGI scripts in Perl that matches your hosting provider (the de facto standard is *.cgi, sometimes *.pl). In Apache, the ownership of a script is determined not by its extension, but by the line "#!..." at the beginning of the script, as in almost all UNIX servers.

When installing all of the above, it is very important for us to be able to run Perl scripts “without a web server,” i.e. like regular programs. This is very convenient when checking them for syntax errors.

You can check the correct installation of everything by writing a simple script:

#!(path to Perl) print "Content-Type: text/plain ; charset=windows-1251\n\n"; print "";

Save this script in a file, for example, test.cgi and put this file in your cgi-bin folder.

Now test the script by launching your browser and executing the URL:

Http://localhost/cgi-bin/test.cgi

If everything is fine, you should see the following output in your browser window:

The script worked successfully! Congratulations!

If, instead of this script output, you saw on the screen the script itself or something like “Access Denied”, “Permission Denied”, “Forbidden” or did not see anything at all (as when loading an “empty” document), then check the settings of your web server - most likely, you have incorrectly set the access rights to your cgi folder.

Now let's try to run our CGI script as a regular Perl program. Let's go to some command line shell (for example, FAR manager) and type:

Perl (address of your script)

As a result, you should see the output:

The script worked successfully! Congratulations!

Instead of words in the last line, “abracadabra” is possible - that’s okay; there is simply a mismatch between the encodings in the script and the shell in which we execute it. The main thing is that it works.

If both of the above tests were successful, congratulations! Now you can debug most CGI scripts on your computer without paying your provider a penny for it! Now you have your own little “internet in miniature” :)))

Techniques for debugging scripts.

A fairly common syntax error is omitting ";" at the end of the statement. (This is especially true for those who are accustomed to BASIC, where the line separator is the separator between operators. In Perl, as in C/C++, all line feeds, carriage returns and tabs are equated in importance to a space and are called "whitespace characters". Separators they are not operators. The only exception is their use in string constants, where they are "themselves", but this only confirms the rule that they do not separate operators.)

So, if your script contains a syntax error, then the message about this error will still not reach the browser. Most often, if there is a syntax error in the script, the server issues the error "500 Internal Server Error". Well, this really is considered an “internal server error”... But what line is it on?!

But we can now run a CGI script "as a program" and see the Perl error message!

If you make a deliberate mistake in the above script by removing the ";" at the end of the penultimate line, then if we run it “via the server”, we will most likely see “500 Internal Server Error” written in capital letters. And if we run it “as a program”, we will see a message like the following:

Syntax error at test.cgi line 3, near "print" Execution of test.pl aborted due to compilation errors.

The first line indicates that a syntax error occurred in the test.cgi file, on line 3, next to the word print. In my opinion, quite comprehensive information! :) (the second line says that the script execution was interrupted due to compilation errors).

Now we look for line 3, the print statement, and fix the error. Also, a rather unpleasant error, leading to, at first glance, completely incomprehensible script behavior, is the omission of the closing curly brace ()). Most often Perl will detect this as a compilation error, but I have had cases where no error was thrown. In general, all errors in CGI scripts can, in my opinion, be divided into the following categories:

  1. Syntax (compilation errors);
  2. Interaction errors with CGI;
  3. Errors in interaction with other programs and/or files;
  4. Brain teaser.

It is most convenient to find the first errors using the method described above.

The second includes incorrect script output: the script must output its response in HTTP format, i.e. response header fields, then an empty line, and then the response body itself. In the example above, the title line was output:

Content-Type: text/plain ;charset=windows-1251

then an empty line - and the body of the response:

The script worked successfully! Congratulations!

In this case, the server, having received a response from the script, parses the header issued by it, adds additional fields and the main response line to it. Therefore, a CGI script does not need to generate a full title. Typically, the Content-Type field is required, but in any case, an empty line after the header must be

A few words about the so-called nph-CGI scripts. These are scripts that completely form the HTTP header. Therefore, the server should not “parse” the headers issued by such scripts, but transmit everything to the browser “as is”. Hence the name - nph (non-parsed headers - unparsed headers). For some servers, such scripts must have a certain file name structure (the name must begin with nph-), for others this is not necessary.

Also, errors in communication with CGI include incorrect specification of CGI environment variables, as well as - for scripts that process forms - the method of transferring data from the form (GET or POST). At the same time, if the script is waiting for data sent by the POST method (to standard input), and the GET method is incorrectly specified in the form, then the script will get stuck - it will wait for data to arrive on standard input! If the script accepts data using the GET method, and POST is specified in the form, the script will execute, but will not receive any data from the form (as if there were no fields in the form).

For scripts that display “pictures” (GIF, JPG), a typical error is the ASCII transmission mode. Immediately after opening a file with the open operator, this file is assigned to ASCII read/write mode, intended for “plain texts” (text/plain), such as text in Notepad.

All files that are involved in the output of the image (including STDOUT !) must be switched to “binary” mode using the Perl operator:

Binary FILE;

Otherwise, the data will be distorted, since it will be transmitted as text: firstly, the “ends of lines” will be replaced, and secondly, the character with code 0 will be perceived as the end of the file.

Errors in communication with external programs and files include incorrect calls, for example, of the UNIX commands sendmail, date, etc. This also includes the incorrect path to Perl, written in the first line after #!.

How can you debug scripts using, say, sendmail on a local machine if you (under Windows) do not have sendmail? The easiest way is to comment out the part of the script that sends the letter. In the general case it most likely looks like:

Open EMAIL,"|path_to_sendmail_list_of_recipients"; print EMAIL "...."; ....close EMAIL;

where in the open statement sendmail is opened, EMAIL is a file descriptor; could be anyone. Thus, you can check the operation of the script without sending a message via E-Mail, if it is auxiliary (for example, in guest books that send a notification to the webmaster about a new entry).

You can do it another way: instead of opening sendmail in the open command, write the opening of the file. There is no need to change anything else.

In this case, when you “send a message,” a file with this letter will be created, and you will be able to manually control its format.

By the way, since the E-Mail address has the form user@hostname , and the @ symbol in Perl is an array designation, the “direct” writing of such an address will cause an error! Therefore, you need to put a backslash \ before @. That is, the address in the Perl line should look like user\@hostname . The same applies to other reserved characters, such as $.

Regarding the date command, it can be said that in most cases it can be replaced by the perl function

Scalar localtime

which returns a string with the current date/time, for example:

Sun Oct 22 16:11:42 2000

Such a replacement is quite possible if the resulting date/time value is not parsed by a CGI script, but is simply written to a log file (or used “as is” in another way).

Thus, in most cases, the operation of the script can be checked even in the absence of the required programs that are standard for UNIX.

Regarding the file connection error, we should mention incorrectly set access rights to auxiliary files used by the script.

Final debugging of CGI scripts on the server.

So, your script works fine on your local computer, now it's time to transfer it to the server.

So, what you should pay attention to:

1. Path to Perl in the first line.

Change it to the path to your hosting Perl. When debugging the script, you either did not need this line at all, or, if you were debugging on Apache, then this path on your computer is most likely different.

2. Paths to other programs used by the CGI script.

3. Names of the files accessed by the script.

On Windows there is no distinction between uppercase and lowercase letters in file names, i.e. A.TXT and a.txt are identical names. In UNIX, on which most Internet servers operate, uppercase and lowercase letters in file names are different characters. Thus, a script that opens the a.txt file with the command:

Open FILE,"a.TXT";

will work fine under Windows, but will not want to work under UNIX (the file will not be found).

4. Mode for uploading files to the server.

The most common mistake is to download the entire site in “binary” mode. And if there are no special problems with html and txt files downloaded in this mode (although they may arise), scripts downloaded in this way _will not work_. All CGI script files, as well as the text files they use, must be uploaded in ASCII mode.

5. File permissions.

Even if everything is done correctly, the script is unlikely to start working immediately after being uploaded to a UNIX server.

In order for it to start working, you need to set the access rights for the CGI script files and the files they use.

As a rule, immediately after uploading files to the site, they are all set to a certain “standard” set of rights (by default), for example:

Rw-r--r--

In general, all files from the point of view of the required access to them can be divided into 3 groups:

  1. CGI script files;
  2. Files used by the CGI script to read;
  3. Files that the CGI script uses to read and write;

Typically, the hosting provider that allows the use of CGI will specify what permissions must be set for each file type.

If not, then the following settings can be used as a compromise:

CGI script - -rwx-r-x-r-x (755); Files to read - -rw-r--r-- (644); Files to record - -rw-rw-rw- (666);

ATTENTION! Some hosting sites recommend other, more strict configurations of access rights that provide more reliable protection against hacking for your site and the system as a whole! So follow your hosting provider's recommendations if you have them!

It so happens that I know at least two people who would like to learn Perl. I decided to write this post especially for them.

  • Part 1: Variable Types (You are reading this part)

In it you will find examples of simple programs from the series “print numbers from 1 to 5” and the like. I have always liked to learn from examples - it is more interesting and faster than from books or seminars. You can also look at the posts on this blog - chances are you will find more examples there.

I assume that at school/institute you studied Pascal/Delphi, C or at least Basic, and there is no need to explain what a function and loops are. If this is not the case, it's okay, you'll just have to spend extra time reading Wikipedia to figure it out. If you don't know how to run a bash script, or why in the first line of the script you should write something like #!/bin/sh, you'll have to do a little googling to find out.

Especially for those who are interested in the questions “is it true that Perl is very complicated”, “what books on Perl can you recommend” and even “uh... is it still written in it?”, I wrote a Mini-FAQ on Perl , which you can read on HabraHabr. And for those who did not strengthen many letters Here I will give a brief summary of it:

  • Perl is a modern programming language that has been written and will continue to be written for a very long time.
  • Perl, like any other programming language, has its advantages, disadvantages and applications. Exists really big class of problems that Perl solves with 5+.
  • Perl syntax is no more complex than C++ or Java syntax. You can verify this by reading this post to the end.
  • There are good, yet inexpensive Perl tutorials. You can also easily find a community of Perl programmers online who speak your native language.
  • Perl works well under both UNIX family operating systems and Windows Evil.

Addition: I also recommend that you read the articles Perl vs Python vs Ruby vs PHP and Priests of Programming. The first talks about the performance of various scripting languages, the second talks about the difference between PHP and other languages. For Python fans, I advise you to read the article Python script performance test. I hope that these materials will help you find the answer to the question “what is good about Perl.”

Hello %username%!

So, let's write our first Perl script already!

#!/usr/bin/perl

$name = shift() ;
print("Hello, $name! \n") ;

Let's run the script:

$ chmod u+x 1 .pl
$ ./ 1 .pl afiskon
Hello afiskon!

Everything is very simple here:

  • The names of scalar variables (that is, not arrays or hashes, what they are - see below) begin with a dollar sign.
  • The shift function returns the next script argument. In other words, the first call to shift() returns the first argument, the second call returns the second argument, and so on.
  • The print() function prints the string passed as an argument.
  • You can substitute variable values ​​into the line (see line 4). For more information about strings, see below.

If it’s not very clear yet, that’s okay. Perhaps a little theory will bring a little more clarity.

Variable types

There are three main types of variables in Perl: scalars(numbers and strings), arrays- similar to those used in Pascal or C (sometimes arrays are also called vectors), and hashes(associative arrays).

Scalars we already used in the previous example. Here are some more examples of specifying scalars.

#!/usr/bin/perl

$a = 123 ;
$b = - 7.496 ;
$c = 0xABC; # equals 2748, yes, it's a comment :)
$d = ($a + $b ) / $c ;
$d *= $a ; # same as $d = $d * $a;

$str1 = "hello" ;
$str2 = "$str1, world" ; # $str2 contains "hello, world"
$str3 = $a . " \n". $str2 ;
$str4 = "$str1" ; # $str4 contains "$str1", not "hello"

Here we set positive and negative, integer and fractional numbers, set a number in hexadecimal encoding, add, multiply and divide - everything like in C or Java. In addition to the above operations, Perl also supports the exponentiation operation:

$a = 2 ** 8 ;

With strings, everything is approximately the same as in some PHP. The dot means the concatenation operation (that is, “gluing” strings together); if the string contains variable names, values ​​are substituted in their place; using a backslash, you can insert newline characters (\n), tabs (\t), quotes (\" ), the backslash itself (\\), the dollar sign without any variable substitution (\$) and much more. If the string is in single quotes, the characters in it are interpreted “as is”, without variable substitution, etc.

Like PHP, Perl interprets scalars as numbers or strings depending on the operation. It's simple:

$int1 = "11" + 22 ;
# ^ the string "11" is converted to a number,
# after which addition is performed, result: 33.
$str1 = "11" .
22;
# ^ the number 22 is converted to a string,

# after which concatenation is performed, the result is "1122".

The rules for converting from a string to a number and vice versa are the same as in PHP:
$str1 = 0 .
"abc" ;
# ^ the result is "abc", the number zero is converted to the empty string
$int1 = "aaa" + 1 ;
# ^ result is 1, there are no numbers in the string "aaa"

$int2 = "12aaa" + 1 ;

# ^ result is 13, only the first digits of the string are taken into account
By the way, there are special operators for declaring long strings - q and qq:
# similar to single quotes
} ;
$text = q (
Do you have $15?
# similar to double quotes
$message = qq (
} ;

Hello, $username! How are you?

#!/usr/bin/perl

Working with Arrays
happens as follows: $scalar = "bebebebe" ;
($a, $b) = (1, 2);
# same as $a = 1; $b = 2; \n";
@arr = ("aaa" , 123 , $scalar , $a + $b ) ;
print $arr [ 1 ] . " \n";

push @arr , $a ;

print pop (@arr) . "

In this script we also call the print and push functions without parentheses. In Perl, when calling a function, wherever it does not cause ambiguity, the parentheses can be omitted.

To declare an array whose elements are strings without spaces, there is a special operator - qw:

@arr = qw/aaa bbb ccc/ ;
# similar to ("aaa", "bbb", "ccc"), only shorter

Hashes are similar to arrays, but the elements in the hash are not ordered. In this case, strings can be used as a key by which an element is accessed.

#!/usr/bin/perl

%hash = ( # when declaring hashes and arrays you can
"x" => 12 , # use line breaks
y => 53 , # if there are no special characters in the key, quotes are not needed
"z" => - 10.5 , # you can leave a comma at the end
) ;

$hash("x")++; # x coordinate is now 13
$hash ( y ) --; # y coordinate is now 52

# display coordinates
print "x = $hash(x), y = $hash(y), z = $hash(z)\n ";

Hash names begin with a percent sign, and curly braces are used to refer to an element (rather than square brackets, as is the case with arrays). If the key name is known in advance, you can specify it without quotes (line 10).

By the way, the $test, @test and %test variables are completely independent variables of different types.

At this point I wanted to move on to conditional statements and for/while loops, but I realized that there was already too much text for one post. Meanwhile, many questions remained behind the scenes:

  • Conditional statements;
  • for and while loops;
  • Declaration of functions;
  • Working with streams and files;
  • Strict syntax;
  • Using ready-made modules and classes.

I will write about this in one of the following posts. I would like to receive at least a couple of comments on this post - interesting/uninteresting, understandable/incomprehensible, and so on. By the way, if you have questions related to Perl (not necessarily related to this post), feel free to ask them in the comments!

I hope this series of posts about programming in Perl will help you write your first simple scripts. Over time, the scripts will become more complex, they will use new technologies (OOP, regular expressions) and after a while you will find that you know enough about Perl to share your experience with others.