Perl programming language for beginners. Perl FAQ for Beginners


This important event in the world of programming occurred in 1986, when a seemingly ordinary guy, Larry Wall, after painstaking work, announced to the world that he had developed the Perl programming language. The path to this significant event turned out to be difficult and thorny, but the result was worth it. How, who and why developed new language programming? Here are the answers to all these questions.

Background

The impetus for this discovery was when he took part in the UNIX project. The work was difficult, as it was necessary to create secure network with many levels, so that it is possible to combine the work of several computers operating at considerable distances from each other. The whole process was completed successfully, but the reports had to be made very labor-intensive, not only with a huge amount files, but also between them.

Wall decided to use the awk filter for the job, but an unexpected obstacle arose: it was impossible to control either the opening or closing of a huge number of files - ironically - based on the information they contained about the location of these files.

Initially, Larry, to solve an unforeseen problem, decided to write a specific system utility. It seemed to be a way out of the current situation. But before that, he had already compiled several utilities to solve this problem, which, unfortunately, did not become a solution for UNIX standards.

That’s why a talented system administrator, a linguist by training, which helped him in his work, took a risk and created the Perl programming language so that he could simultaneously process text files, find solutions to system problems, and create more understandable reports. And at the same time, it should be low-level programming that would be accessible in the C language. That is why the Perl interpreter was written in it.

New programming language: the reason for its occurrence

According to Larry, laziness helped him create a new language. But it was precisely that laziness that made it possible to decide important task: How to avoid creating a large number of programs on different languages, which were an integral part tools UNIX. This procedure was too tedious.

The merits of the new language were appreciated by others, since it harmoniously combined the capabilities of file processing and system administration. And these are exactly the two necessary facts that are needed when programming a UNIX system.

It should be noted that the Perl programming language has a slight difference from other similar languages: it appeared because there was a need for it, and not in order to amaze users or come up with another beautiful tool that will not play a special role.

On the contrary, when Larry introduced users to his invention, among system administrators it created a real sensation, because now there was no need to spend a lot of time to understand several programming languages, and it became possible to easily solve problems by using a single language using a symbol table.

Peculiarities

Translated into Russian, the acronym Perl sounds like “a practical language for extracting data and creating reports.”

They decided to make a camel as a symbol of this type of language, probably considering that since this animal is noble, hardy, capable of bearing a heavy load for many days without complaint, the same work resembles the load on a new language, which is also serious.

There are many reasons why the new language was immediately appreciated by many users. Anyone who uses the UNIX system knows that settings here are made through special files - ordinary text files, and changes are made after executing commands. They are written in a special shell language and are executed from the command line.

The UNIX system allows you to create custom commands by drawing on and storing interpreter commands. They remain in text files and, if required, are executed as a standard set of operating system commands - only through the command line.

User commands otherwise called scripts. IN UNIX system the operational administrator has to write a large number of scripts, which, in turn, process subsequent scripts, i.e. text files using special programs:

  • Awk. The program makes it possible to compare with these samples and serves as a report generator.
  • Sed. Acts as a batch editor for text files.

Programs read lines of input files one by one as filters. They then perform the actions that apply to the string, which are determined by the program commands. In this case, a chain of characters is selected according to certain patterns, replaced according to established rules, and new files are generated.

Great opportunities

The new programming language Perl has opened up very rich possibilities in cases where it is necessary to process text and stable expressions. Perl has a large variety of helper modules.

Over time, this unique language has expanded its boundaries and is now widely used in web development and games when network programming or graphical user interface is needed.

The language has taken root and is loved for its ease of use; now it is recognized as the most dynamic language programming. It supports a variety of paradigms, which include styles - functional, procedural and others, it has memory control, and support for text processing.

It’s not for nothing that one of L. Wall’s mottos says that simple things can remain simple, but complex things must be done.

It's easy to master the language once you understand assignment expressions, code blocks, control structures, and functions.

Similarities with other languages

Larry borrowed a lot from other programming languages. For example:

  • UNIX shells. Variables are marked with leading characters, they clearly express the type of the variable and help these variables be interpolated in strings. Built-in functions provide instrumentation, and this is used to program the shell.
  • Arrays from Lisp.
  • Using Perl regular expressions from awk, at the same time borrowing associative motifs from him.
  • From sed.

But the new language coped with its own tasks much faster, and therefore they began to use it not only for solving system administration problems.

Wall obtained a package from G. Spencer that helped him master Perl regular expressions, modifying it to suit his brainchild. Many of the features developed are not solely due to Larry. Colleagues and friends tried no less enthusiastically to bring their innovations to the unique program being developed. And when the language appeared on the Internet, a whole community of like-minded people formed who also helped improve it. Since then, according to statistics, more than 10,000 programmers have been involved in the work.

However, the language is still being improved thanks to the development of packages that are used successfully in implementing new applications of the language for developing technologies related to information.

Stages of development

Small but significant stages of the journey can be highlighted in the table.

Released versions

Time of creation

perl 1. Didn't contain many features. This was the easiest way to search files using patterns. But there were file descriptors, format and scalar variables.

1988 January.

perl 2. An as yet unimproved regular expression mechanism has appeared.

1988 June.

perl 3. Developers have achieved the ability to process binary data streams.

1989 October.

perl 4. Appeared largely thanks to the book that was published, “Programming Perl", but under the name better known as "Camel Book". The new language has been documented. This period went through a whole series of releases, eventually settling on version 4.036. It was already 1993. Then work began on the next - V - version.

1991 March.

perl 5. Added support for complex data types, object model, which includes references, packages, and a closure as a value. A mailing list is created so that work can be coordinated across different platforms. In fact, it became the main forum for development, porting and maintenance. Modules are now with important part versions, because they were able to expand the language, but without modifying the interpreter. This was able to stabilize him, but expanded his language capabilities.

1994 October.

Unique Perl - programming language: pros and cons

Perl 5 is actively being developed and is now being updated with new versions. But all developments have several factors in common: automatic data typing is carried out, and memory is automatically controlled.

Thanks to the interpreter, not only the types, but also the memory requirements of each program object are known, and it is not difficult for it to allocate memory and free it when counting references.

It should be noted that Perl programming distinguishes the interpreter from others. Proof of this is the translation of the program into intermediate bytecode, and only then it begins to be executed. In comparison: the traditional one works a little differently - the entered operator is interpreted and executed instantly, which is fraught with syntax errors during the workflow. Perl allows you to detect these types of errors already during the translation into buy code.

In order to translate one type of data into another, an automatic process will be required, but if translations of any types of data are impossible, this can lead to a fatal error.

The merit of version 5004 is that there is a UNIVERSAL package, which gave the language a main object, and all classes were derived from it - on an automatic basis. It is now possible to request the version of modules. It has become a reality to support requesting the version of modules. In addition to this, perl began to support many operating systems, and Microsoft Windows including.

Version 5.005, released in 1998, significantly improved the quality of the regular expression processor, improved new hooks in the backend, which was solved with the help of certain modules, and expanded support for operating systems.

Latest updates

The year two thousand gave the world a new, 5.6, version of the Pearl language. It already looked much more solid than the first ones, had 64-bit systems, was able to support files larger than two GB, included string representation taking into account the Unicode standard, and also keyword- our. During this period, the version naming scheme changes to be more similar to other open source projects.

An interesting fact is this decision: if a version is in development, it will be assigned a number with odd numbers, and the stable one will receive an even number.

Wall then asked his followers to make suggestions for creating a more advanced version. His call was heard, and the result was 361 documents, which helped develop version VI. The users were presented with a document that most likely resembled a summary, and this version existed, but only in the form of a description of the language. A number of documents became the specification for this version. An attempt to launch version VI interpreter in 2006 was stopped. But since 2009, under the name Rakudo Perl, this version has lived and is periodically updated.

A significant change in the Perl 5 development process occurred with the release of Perl 5.11. The developer community has moved to a monthly release cycle, with release dates planned three months in advance.

A new version

Version 5.8 appeared in 2002. It is famous for the fact that from that time it was updated annually until 2008, it significantly improved Unicode support, added many functions, which include multithreading support, an original I/O implementation, and increased numerical accuracy. And, again, new modules appeared.

On the 20th anniversary of the creation of a general-purpose programming language, the new version numbered “5.10.0” did not disappoint users once again. New operators have appeared, as well as “smart” matches, and regular expressions have been updated.

What have the last years of work brought?

Every year, new improvements helped make the language invented by Wall easier, simpler and more accessible. The year 2010 was marked by the fact that the syntax of the Perl language received support for package NAME VERSION, regular expressions; in subsequent years, modules were updated, and support for operators was expanded.

The goal was achieved - to indicate during operation the version that should be emulated, which means to allow perl to be updated, but at the same time not to lose the working capabilities of the used scripts, which pose a threat of being incompatible with the presented one new version. There are more functions and increased security.

At the end of May, just recently, the next version appeared, as always, more improved and easier to use. Today, anyone can test it and see from their own personal experience that a lot of work has been done to create this programming language.

In this Perl language, arrays are not limited. Using the language, you can solve non-traditional tasks that would otherwise require several people, perform administrative tasks, process text files with high quality, and not much time will be spent on all the problems. By developing new programs, using a symbol table, using the necessary operators, the result will be correct and fast.

This article once again proved that nothing is impossible for enthusiasts of their craft. Sometimes even the smallest problems lead to useful discoveries that can make our lives a little easier.

The preface, in our opinion, should give the reader information on the basis of which he decides whether he needs this book.

What is our book about? It is, naturally, about the Perl language, because that’s what it says in the title. Who needs it, this Perl? Those who create CGI scripts, administer the system by writing scripts rather than clicking the left mouse button, process texts, solve many other tasks from related areas and at the same time need a powerful, but easy-to-use tool that allows you to create large programs and small programs and quickly try them out. It is also useful for those who teach programming to have an understanding of this language, as it has interesting properties that are missing in traditional programming languages ​​used in the teaching process.

We like some features of the language: the dependence of the result on the context, associative arrays, the typeglob data type, packages, implementation of object-oriented programming and, of course, text processing tools. If you are not interested in at least finding out what it all means, then you can put the book down. If you already know everything listed above, then you can also put it aside, because this book is for those readers who are just starting to learn Perl on their own.

The Perl language was created by system programmer Larry Wall as a UNIX tool that allows you to “glue together” large scripts from programs that perform individual functions to solve a set of tasks related to administration, text processing, etc. Later he went beyond these framework, turned into real language programming, which reflected many of the trends that have emerged in programming technology over the past decade, and has become widespread in connection with the development of the Internet. Perl is the main tool for creating CGI applications, convenient for solving problems of administering Web servers, e-mail and other systems. Thanks to the speed and ease of writing scripts in this language, it has spread to other platforms: DOS, Windows, OS/2, Mac, VMS, etc. One of the main advantages of the Perl language is its openness and accessibility. IN Internet networks You can get completely free source codes for the Perl interpreter (Perl is an interpreted language, which in some cases is an advantage) and its extension modules.

This book is a self-instruction manual for the Perl language, which is studied, as they say, from scratch, i.e. it is assumed that the reader is not familiar with this language - he will learn everything he needs by consistently studying the topics and consolidating the material covered, answering questions and performing exercises, given at the end of each chapter. Let us repeat that the proposed material represents only the basics of the Perl language. This book is in no way intended to be a textbook on Perl programming. In it you will not find a programming methodology or ready-made recipes for solving problems, it does not detailed description the most commonly used modules and solving problems with their help, but after reading the book you will acquire basic knowledge, which will allow you to understand any Perl script.

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, data can be a number or a string of characters.

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, next command uses the Perl debugger to print out the number 0177 octal system, corresponding to the number 127 decimal:

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 serves as a directive Perl language finish execution and display the 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. At the same time, with the help for expressions The values ​​of each element are displayed:

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

The written for loop can be replaced with 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.

Consider the following comparison example:

$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 this case, the expression takes 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 does not implement a 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, statements must be enclosed in curly 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'll learn later, the continue block gives the script more control over the process than a 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 a dynamic instruction by assigning the value of a variable to text, which actually contains the required Perl 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 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 the sub keyword as shown 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 of the shift function:

# 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 an 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, next instruction 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 the MS-DOS operating system, the symbol new line 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 a character string, Perl 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 file processing functions, but also some very convenient functions to scan 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. To read a list of files contained in a 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

Being, in a sense, a replacement 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. Stick to it general rule do not execute external commands from a Perl script. However, if you are forced to do external commands from the script, you can use the built-in ones for these purposes system functions, exec or fork.

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 and serving to designate a pattern consisting of symbols. 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 characters used by Perl scripts in regular expressions.

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 statement below, Perl replaces the part of the string that matches the pattern with 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.

All of the following in no way claims to be complete or accurate.

I want to warn you in advance that this article will not make you a super PERL programmer, but it will give you some necessary initial information, which will help you further study this most interesting language programming.

I decided to write this article after I learned how difficult it is to “get the hang of” everything, even if you have some kind of PERL manual at hand. Everywhere, already at the very beginning, they begin to refer to some mysterious terms and commands, and you can only blink your eyes in surprise, or (if you still understand something) make these programs work (not “as it should”, but in general !). This article could be called “PERL for dummies” if it covered all the material, but here my goal is to give you only the necessary initial concepts, and so to speak “prepare you for further battles” :). Although it is quite possible that in the future, “at the request of the workers,” this small article will grow into something more.

So... let's begin!

First, let me tell you that PERL must be installed on your computer. Some of my friends completely skipped this seemingly simple operation, and then, having written a simple program, they tried to run it for a long time... ;) Most available package PERL (in my opinion) is ActivePerl, although this package is aimed at Windows users, and if you have UNIX, you can download something native from www.perl.com. One way or another, you will get it and install perl for yourself (if you have not already done so). So: you will have a new “perl” folder, but this does not mean that all programs need to be placed there :) Perl, sitting there, only executes all your ingenious creations with the *.pl extension, and where they themselves are located - one user knows :) (true for windows users with the ActivePerl package installed, because it associates *.pl files).

Because Since this article is intended primarily for Windows users, I consider myself obliged to tell you that for programs executed in this operating system it is not at all necessary to start each program with the line:

#!/usr/bin/perl

The thing is that this language was created on the basis of the UNIX OS, and they are trying to transfer this line to us as a “legacy” from their operating system. However, you should remember that the server (if you decide to upload your programs there) may also have UNIX installed.

Now a little about the writing method.
I advise you to start using a simple notepad to remember all the commands and programming syntax. In the future, you can use some kind of editor, but this is no longer fun :), and even more undesirable for those who are just getting acquainted with this programming language, and programming in general.

Almost all tutorials on this language start with the simplest program, which looks something like this:

print("hello, WORLD!\n");

Some of you have probably already copied the above program to your file and noticed that it opens quickly and closes just as quickly. This is due to the fact that the program is a program, and after it is executed it will immediately close, so add another line to the program with the following content:

In the end it will all look like this:

print("hello, WORLD!\n");
<>;

It doesn’t look so simple for the uninitiated... Even a little scary... But this is only for the uninitiated, in fact, everything can’t be simpler! :) Can't believe it? I'll prove it now.
First, you need to know that print is a command that outputs information to the standard output STDOUT (STanDart OUT or, more simply, monitor output).
Secondly, incomprehensibility in the form \n is a transition to a new line, but not the program, as some might be afraid, but the information on the screen, i.e. if you were to continue the text enclosed in quotation marks, then after this character it would be printed on a new line. And if you need to use a backslash (shels:) in the text itself, then you need to put another shels before it. For example:

print "\a"; #Command after which Perl #will output a signal to SPICER print "\\a"; #Perl will simply print \a

Then I want to make you happy: there is no need for parentheses :) Their use depends entirely on your mood, although the manuals say that this supposedly helps highlight text in the program. In general - whoever you like more...
As you probably already guessed, quotation marks are needed to enclose text in them, so there are two unclear points left. But before I dwell on them, I think it is necessary to explain to you what kind of information exists in Perl.
The fundamental unit of information in Perl is the scalar, i.e. a separate value stored in a separate variable.

$a = "hello, world!"; #Assign some text to variable $a
$b = 777; #Assign variable $b some number

These variables store strings, numbers, and references. In this case, it is necessary to understand the difference between numbers as such and the numbers contained in the string.

$abc = "123"; #Number in line
$123 = 123; #Number as such

If you need a number for calculations, then simply do not use double quotes.

The semicolon at the end of each line is actually... the end of the line, which means that you can write the entire program in one line, but we feel sorry for the lines or something :) There is an exception to the above: the # sign indicates that everything that is in the line after it is a comment and no longer relates to the program.
Diamond sign<>- this is the default or, speaking in clear language- standard input from the monitor (I’ll explain: a request appears on the monitor, and you enter, of course, through the keyboard. Then you press enter and the entered value is already in the Perl variable, if it has been set). The whole trick to adding this diamond in our case is that it will ask you for this input until you press the "enter" button, and since the program does not indicate what to do with this input, perl will simply forget about it and will consider our program complete. And as a result of executing this program, you and I will see the text Hello, world! on our monitors. .

Now let's complicate our program a little:

print "enter your name: ";
$name =<>;
print "hello $name!";
<>;

You should understand that programs are executed line by line, i.e. first the first line, after it the second, etc.

So, on the first line we are prompted to enter a username. In the second line we read it into the $name variable. $name is, as mentioned, a Perl scalar variable that begins with a dollar sign. Looking ahead, I’ll tell you that in addition to variables starting with a dollar, there are also arrays (@array), hashes (%hash), and several other types that are too early to talk about. There is equality between the variable and the diamond, which means that we assign the result of the query to the variable. In the third line we print the word hello, and after it we print what was stored in the $name variable. In our case, this is the name that we asked you to enter.

Let's take another diversion in which I tell you what you can do with variables... You can do ANYTHING with them! And this is not an exaggeration. For example, this is possible:

$a = 3;
$b = 4;
$c = $a+$b; #Add two variables and
#assign them to third
print $c; # Print the resulting number
print $a+$b; # the same thing, only without
# bringing in a third variable

I hope everything is clear with this... In the meantime, some people get it, we will write a program that executes DOS dir commands. For those who don’t know, dir is a command that displays the contents of the directory in which you are located.

$dos = `dir`;
print $dos;
<>;

This program reads into the $dos variable the result of executing the dir command, which is enclosed in back quotes (if these were simple quotes, it would not be a command, but just a word) and then displays this very result on the monitor.

Now, so to speak, let's return to our sheep, or rather, only to the lambs for now :) We learned how to display the text we need on the screen, receive information from the user, and also learned that DOS commands in back quotes will be executed as DOS commands :) It's time to write a program that will ask for nothing more than these same commands:

print "enter command: ";
chmod($com =<>);
print `$com`;
<>;

For security reasons, I highly do not recommend entering the FORMAT command, guess why :) Among the innovations, we need to highlight the appearance chmod commands(). This command removes the newline character \n from the information we receive in the request, which is there by default. What's on the second line is a shorthand version of two lines:

We only gain a few characters with this, but it’s still nice :)

At this point, I believe that you have completed the first steps and are ready to continue the thorny path of learning Perl.

However, the most widely used scripting language is Perl.

This chapter is about the Perl language and its uses. Once you learn to program with Perl, you can use it to write scripts that solve a variety of Internet and Web programming problems.

Particular emphasis will be placed on those features that are used when writing CGI scripts. If you've never programmed in Perl before, use this chapter as a starting point to learn it.

The concepts you'll be introduced to in this chapter will teach you how to write professional Perl scripts.

The chapter covers not only the basics of Perl programming, but also several other aspects. By the time you finish reading this chapter, you will be able to understand the following key concepts: Perl is an interpreted programming language specifically designed for text processing.

Programmers often refer to Perl programs as scripts. Using Perl, programmers create CGI forms.

P erl supports operations with files and databases. This makes it well suited for storing and retrieving information according to the needs of Web users.

P erl comes with a debug program that you can use to test your Perl code

In this section:

8 PERL programming language
This article will introduce you to the Perl language and give you comparative characteristics Perl and C/C++, will talk about the richness of Perl.

8 Using PERL
Principles of using Perl, or what can be done using Perl.

8 Introduction to PERL
Basic concepts of the Perl language, first example.

8 Installing PERL
A light hint on how to install Perl.

8 Using the PERL Debugger
Basic principles of working with the Perl debugger; debugger commands; examples of using.

8 Data Types in PERL
The chapter is devoted to data types and the transition from one type to another

8 Variables
Perl supports three types of variables: scalars, arrays, and associative arrays. That's what we're talking about. ;-)

8 PERL statements
Overview of Perl's basic operators.

8 PERL language constructs
Description of Perl syntax features. Basic operators.

8 Subroutines
Syntax and semantics of routines in Perl.

8 String Processing
Description of functions for processing string variables.

8 List Processing
Several functions that expand the range of possibilities for working with lists.

8 Working with Arrays
Perl contains several built-in functions that help you work with array elements.

8 CGI scripts using PERL
In this chapter, you will learn to use Perl to create CGI scripts.







2024 gtavrl.ru.