Introduction to Perl (1)

Source: Internet
Author: User

What is Perl?

Perl is a free and open-source scripting language created by Larry Wall. This language is mainly intended for practical and rapid development,

Structured Programming is incompatible with the popular object-oriented programming.

However, this does not prevent Perl from being widely used and widely used. It is very active around Perl in the world.Community,

Many people continue to help improve the documentation and create examples.Code, Provides some third libraries, and so on.

You can visit the following two webpages: www.cpan.org and www.perl.com.

Perl is the most famous and best at processing data in several texts. In many other languages, it takes tens or even hundreds of lines of code to complete tasks,

Perl may only need a few lines of code. However, these advantages come at a cost. In fact, the style of Perl code writing is often criticized. A typical process-oriented language.

There is also the philosophy that Perl has always adhered to: as long as there is no conflict or misunderstanding, the code can be written in multiple forms --There's more than one way to do it

This leads to the loose and random Syntax of Perl. The same thing is often written in a variety of different ways, and some seem strange,

In terms of syntax, Perl has many symbols, making it hard to learn and forget Perl to a certain extent.

This article briefly introduces the basic syntax of Perl. It aims to show you how to write Perl and read other people's code smoothly.

The languages of the world are connected to each other to a certain extent. If there is a language foundation, you can learn another language,

It will not be too difficult to get started, but it will take time to get started, be familiar with it, and use the third database.

 

This section describes various data types.

 

(1) Statements and comments:

The Perl statement ends with a semicolon (;) and uses # As a line comment. There is no cross-line comment in other languages.

The code block is enclosed in braces, which is similar to C.

However, this braces are mandatory in some places, such as in if, for, do, while and other statements.

Unlike other languages, it uses indentation to determine the block.

(2) variables: Scalar & list)

Perl refers to simple data types, such as strings, numbers, and other "singular" items collectively referred to as scalar, which is opposite to the "plural", such as arrays.

Scalar declarations start with $, for example, $ STR = "ABC"

Multiple scalar values can also be declared together:

($ X, $ y, $ z) = (11, 22, "no", 4 );

 

The array declaration starts with @, for example, @ arr = ("ABC", "EDF ")

The variable declaration in Perl is the same as that in many other scripting languages. You do not need to specify the type. You can directly declare the value assignment.

If it is declared but not assigned a value, Per will assign it the value UNDEF by default.

To check whether a variable has been assigned a value, Perl provides the operator defined to determine whether a variable has been assigned a value.

If (! Defined ($ myvar ))

{

Print "uninitialized variable ";

}

(3) String

(1) Basic syntax

In Perl, all strings are enclosed by double quotation marks or single quotation marks, for example, "string" 'string '.

These two methods are often the same. The difference is that when other variables or escape characters appear in the string, double quotation marks expand the content of the variable, while single quotation marks do not.

This is similar to shell script.

For example:

$ Var = 234;

$ Str1 = "str1: $ Var"; # print it out and get it-> str1: 234

$ Str2 = 'str2: $ var'; # print it out and get it-> str2: $ VaR

 

(2) Splicing

The dot (.) is used to concatenate strings. This is different from other languages that directly concatenate strings.

Use the DoT number to connect the string, for example:

$ STR = "ABC". "EFG"; # abcefg

This usage is consistent with shell script and VIM script.

(3) Comparison

It should be emphasized that the comparison of strings should be used:

    • Lt is less
    • GT>
    • Equal to EQ

Instead of using ==, >=, <=, these symbols are used to compare the numerical type.

 

(4) array

(1) Statement

As mentioned above, an array is a variable in the form of plaural. Its Declaration starts with @, followed by the initial values in parentheses.

@ Arr = (12, 34, 56 );

The element types in the same number of groups are not necessarily the same. The following statement is also valid:

@ Arr = (12, "ABC", 'C ');

You can also declare an empty array:

@ Arr = ();

When declaring a string array, you can use the Q, QQ, and QW operators to simplify operations. Q stands for quoted, and QW stands for quotedword.

@ Arr = QQ (ABC); # equivalent to ("ABC ")

@ Arr = QW (abc ef gg); # equivalent to ("ABC", "Ef", "GG ")

@ Arr = Q (ABC); # equivalent to ('abc ')

 

From the above we can see that the difference between QQ and QW is that QQ adds double quotation marks to the whole content in brackets.

QW is separated by spaces. For example, double quotation marks are added to ABC, EF, And GG respectively.

Q is similar to QQ.

The advantage of these operators is that it is much easier to add escape characters, quotation marks, and other symbols to a string.

Qq (\ ABC) eq "\ ABC"

Qq ("ABC") eq "\" ABC \""

 

(2) array access, insert

If you want to add the element in the number group, add the following method in brackets. Like in many other languages, the array element of Perl starts from 0:

Print $ arr [2];

Someone may have noticed that $ is used when the element is referenced, instead @.

In fact, there is a principle that @ represents the entire array.

$ Is used to reference the element.

The same principle applies to hash-type arrays.

 

No size is specified for the array in Perl. If no defined element is accessed, UNDEF is returned.

@ Arr = (1, 2, 3 );

$ Ele = $ arr [20]; # ele = UNDEF

If you want to add a new element to the array, you can also directly use brackets + subscript

$ Arr [4] = 4; # insert if there are no 4th elements and overwrite if they exist.

(3) Conversion

Here is a question that reflects the Perl style. As mentioned above, when @ is used to reference an array, it indicates the reference to the entire array,

However, such references indicate different meanings in different scenarios:

@ Arr = ("ABC", "Ed ");

Print "arr: @ arr ";

The print above will extract the elements in arr one by one to expand and print. This is easy to understand.

But what if I write it like this:

$ SZ = @ arr ;#

Assign an array to a scalar. Perl assigns the array size to the variable on the left.

In the above example, $ SZ is equal to 2.

If Perl cannot determine whether the current context is a scalar or an array, @ arr expands the array by default:

@ Arr2 = (1, 2, @ ARR); # arr2 = (1, 2, "ABC", "Ed ").

But what if I want @ arr to process it as a scalar? The above statement cannot be used.

Perl requires that if you want to specify the type to be converted to scalar, you need to add the Keyword: Scalar.

@ Arr2 = (1, 2, scalar @ ARR); # arr2 = (1, 2)

(4) sort

Perl provides the sorting operator sort for arrays.

By default, the elements in the SORT logarithm group are sorted alphabetically, and thenReturns a new array. The old array remains unchanged..

@ Arr = ("ABC", "rsz", "Ef ");

@ Newarr = sort (@ ARR );

# Arr = ABC rsz EF newarr = abc ef rsz.

If the characters in the array are not stored, or you do not want to sort by character, you can specify to sort by number.

Sort ({$ A <=>$ B} @ array)

Braces indicate a comparison function. <=> they indicate a numerical comparison. $ A $ B indicates two numbers for comparison. These two variables are pre-defined variables that cannot be changed.

If we change the order of A and B, it indicates the reverse order.

If numerical values are used for sorting and the array contains string elements, the strings are treated as 0. If multiple strings exist, the strings are still sorted in alphabetical order.

For example: @ arr = (22, 44, 33,-12, GG, HH)

Sort ({$ A <=> $ B @ ARR); # result:-12 Gg HH 22 33 44

(5) Insert and delete.

Perl provides functions such as push, Pop, shift, and unshift to perform operations such as inbound and outbound operations on arrays.

Push and pop are at the end, while shift and unshift are at the head.

@ Arr = ("AB", "BC", "ee ");

Pop @ arr; # result: ("AB", "BC ")

Push (@ arr, "hh"); # result: ("AB", "BC", "hh ")

Shift @ arr; # result: ("BC", "hh ")

Unshift (@ arr, "VV"); # result: ("VV", "BC", "hh ")

(5) hash Array

(1) Declaration and preliminary implementation

The hash array in Perl is similar to dict in Python and map in C ++.

The array stores a pair of <key, value> values.

The hash array is declared by %.

% Hash = ("key1", "value1", "key2", "value2 ");

Print "V1: $ hash {key1}"; # print out: value1.

The above initialization statement is poorly readable when there are too many keys and values.

Therefore, Perl provides another method.

% Hash = ("key1" => "value1", "key2" => "value2 ");

The effect of the symbol => is exactly the same as that of the comma, but it seems that it is easier to identify which is the key and which is the value.

(2) Insert, delete, and modify

The syntax of hash insertion and modification is exactly the same.

% Hash {"key"} = "value ";

If no "key" exists in the hash array, insert it. If "key" and corresponding "value" exist ",

If the corresponding "key" exists, change the corresponding value to the new "value ".

 

Perl provides a delete operator to delete elements in a hash.

For example, delete $ hash {"key "};

 

(3) obtain key and value.

Perl provides the word keys and values to obtain all the keys and values in the hash. The two operators return an array.

For example: % hash = ("K1" => "V1", "K2" => "V2 ");

@ K = keys (% hash); # K = ("K1", "K2 ")

@ V = values (% hash); # V = ("V1", "V2 ")

 

 

This section describes some common data types in Perl. It can be seen that the Perl syntax is very simple, but there are many details.

It is not difficult to get started, but it takes some time to get started.

This article takes a long time. First, let's take a look at the basic branch loop control and functions in the next section.

Coming soon.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.