Introduction to Perl syntax

Source: Internet
Author: User
Tags bitwise square root perl operator

Introduction to Perl syntax

1.PERL variables

    • 1.1.Perl Variable Classification

    • 1.2.Perl variables

      • 1.2.1 Scalar variable

      • 1.2.2 Array Variables

      • 1.2.3 Scalar and array variables

      • 1.2.4 Associative arrays

2.PERL operator

    • 2.1 Arithmetic Operators

    • 2.2-bit operators

    • 2.3 Comparison Operators

    • 2.4 Logical operators

    • 2.5-character operator

    • 2.6 Assignment operators

    • 2.7 Lvalue

    • 2.8 Table Operators

    • 2.9 File Test Operators

1.PERL variables

1.1.Perl Variable Classification

Perl variables are divided into scalar variables, array variables, associative array variables, Class 3. Perl's variables are case-sensitive, such as: an,
An,an is 3 different variables, but different types of variables can use the same name, for example: Var can be a scalar
Variable, and you can also have an array variable that is also var. This is because Perl uses a separate name for each type of variable. Null
, in addition to the Perl variables, you can store any type of data without declaring the variable like C, and the data type will automatically
The Perl variable also has a global and process variable, the default is the global variable.

1.2.Perl variables

1.2.1 scalar variable (scale)

A scalar variable can hold only one value. The scalar variable name in Perl always begins with the character $. The following Perl statement takes 9 of this
The value is assigned to the scalar variable $nine. Assign "Bati" to the scalar variable $name. Then print it out with the print statement.


Save the above statement as a file, and then in a DOS environment (Win9x MS-DOS mode can) run:
C:\perl5>perl (carriage return)
Bati is 9
(What's so familiar??) Yes, Perl is so similar to our usual C.


1.2.2 Array Variables

An array is a table that can store more than one variable at a time. Its assignment method is as follows:

@weekdays=(‘Sun‘,‘Mon‘,‘Tue‘, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’);
     Print (@weekdays); #output to: SunMonTueWedThrFriSat
     Print ($weekdays[1]); #output to: Sun
     @[email protected][1..5]; #At this time, the value of the array work is (‘Mon‘, ‘Tue”,..., ‘Fri’);
     @none=(); #means an empty array

The array variable name begins with @, [] is the subscript value of the array, and the subscript value starts at 0. This is still very similar to C.
Similarly, in Perl, if there is only an array name, and ignoring the subscript, it will output the entire output like C, for example:
The first output statement.
Note, however, that when you output sun, when we refer to a value in the array, we no longer use @, but
Use $ as the beginning of a variable, because it is a scalar variable in terms of a single value, so (this is not the same as C OH)
Of course, you have to give the subscript value.
In the statement that assigns a value to the array work, we use the slice initialization array, you don't have to care about what is slice, you
Just remember this form, in fact slice is a part of the form, is official expression.
The assignment of an array is varied. All we see in front of us is the value array assignment, and you can also use the variable
Or the value of another array is assigned to the array, for example:

    @say=(‘He said‘,@saysomething);

Here is an example of slice:

    @[email protected][0,6]; #Arrayweekend value (‘Sun‘,‘Sat‘)
     Print(@weekdays[1..5,0,6]); #output result is ‘MonTueWedThuFriSunSat‘

Perl also supports a special constructor, $ #var, which is used to return the last index value of an array. For example, the following statement
Use the $[constructor to determine the first index value of the array, use $ #var确定数组最后的索引值, and then display the entire array:

    for ($i=$[;$i<=$#buffer;$i++) { print $buffer[$i]; }
The above statement has the same output as print @buffer;

1.2.3 Scalar and array variables

The table constructor (,) is very similar to the sequential value operator (,). Therefore, which operator is called by Perl depends on the command file
The specifics of the runtime, that is, whether the file is using an array or a scalar value. Perl calls the table-structure character in the array expression,
The count value operator is called in the sequencer value. Consider the following two expressions:


The first statement initializes an array, the second sentence sets the value of the $a_scalar variable to 5, and cancels the assignment of the first 4 elements
The value function.
Let's look at one more example:

    print $assoc{1,2};
    @print $assoc{1,2};

The first sentence prints an element value of the two-dimensional associative array, while the second sentence prints the two element values of the one-dimensional array.

1.2.4 Associative array variables

Associative array variables are similar to array variables, and can store a table of scalar variables. The difference is that the array variable must be
An array element is referenced by an integer subscript, and an associative array variable can access the array element by any value as a subscript
. The subscript of the associative array we call the key value (key), which is an index value. Here's an example to understand:

    print @ages{‘Bob‘,‘Mary‘};
    print keys(%ages );
    for $name(keys(%ages))
        print "$name is $ages{$keys}\n";

The program assigns a value to the ' $, ' variable so that later output of the print statement is affected, about the special variable ' $ ', ' we
will be introduced in the future. When Perl calls an associative array variable, it uses the curly brace {} to enclose the key value.
@ages {' Bob ', ' Mary '} gives the key value within the curly braces, indicating that an element is referenced, and that there are two key values in the statement that indicate
As part of the array, the result should be (35,25) the same as the result ($ages {' Bob '}, $ages {' Mary '}) statement.
The keys operator is used by print keys (%ages). The result returns all the key values of the associative array, forming a table.%ages
Represents a reference to an entire associative array.
Notice the print statement in the Loop statement, where we see the use of the insert variable in the "" (double quotation mark), which is extremely
Used. In the output, the variable is replaced with the value of the variable as the final result of the output, which is called interpolation. But Perl
Inserting a variable in ' (single quotation marks) is not allowed!!!!

2.PERL operator

2.1 Arithmetic Operators

Perl Although the variables and data types are very different from C, but its operators and C are almost the same, except for the type of C
Conversion operator type, pointer reference operator *ptr and struct member selector, and other C operators appear almost entirely in the
Perl, Perl has added several new operators, such as character handling.
There are several arithmetic operators that are supported by Perl to date:

   + addition operator
     - Subtraction operator
     * Multiplier
     / Division operator (only for floating point operations)
     % modulo operator (only for integer operations)

Here are some examples of Perl arithmetic operations:

    print ($x+2*$y);
    print (7/$y);
    print int(7/$y);
    print (7%$y);
    print (7.5%$y);

Perl also supports increment and decrement operators:

    ++ Add
    -- Decrement

Perl added the exponentiation operator: * *, see the following example:

    $x=2**3; #2 of the 3rd power
    $y=2**0.5; square root of #2
    $z=-2**-3; #Results are: -0.125

2.2-bit operators

The bitwise operator processes the integer form of a binary expression, and the result of the operation is an integer. If the operand of the bitwise operator is
Strings or fractions, Perl first converts them into integers and represent them in 32-bit long integers. Perl Branch
Hold all C-language operators:

    | Bit or operator
    & bit and operator
    Bit non-operator
    << Bit Left Shift Operator >> Bit Right Shift Operator

For more information about bit operators, see the C language, and here are just a few examples:

    Print $x | $y; #Result is 7 (binary representation: 111)
    Print $x & $y; #Result is 1 (binary representation: 001)
    Print $x << 2; #Result is 20 (binary representation: 10100) print $x>> 1; #Result is 2 (binary representation: 10)

2.3 Comparison Operators

The function of a comparison operator is to compare the values of two operands. Perl converts the number of character operands to numbers before the comparison operation. Perl uses a specialized string comparison operator to perform table operations on pure characters.

Operator Equivalent string Meaning
Not equal to
Greater than
Less than
Greater than or equal
Less than or equal
Not equal to (result signed)

The 2.4 logical operator logical operator tests the value of a Boolean expression, and the result is true or false. Perl considers that each operand of a logical operator is
is a Boolean value (that is, true or false). The logical operators of Perl include:

   || logical OR operator;
    && logic and operator.

Perl happens logical expressions in order from left to right. When an operand of a logical OR operator is true, or when the logical
When one operand to the operator is false, Perl terminates the calculation of the logical expression. Perl uses this short circuit to gauge the value
Quickly evaluates the value of an expression., these two operators are also called short loops and and short loops or.
In addition to the above two operators, there are three logical operators:

    ! Negative operator
    ?: conditional operator
    Sequence value

Operator! A Boolean value that negates the operand, which is equivalent to a logical non.? : The conditional operator, which has 3 operands, expressed in the following form:


The following statement passes? : operator, which implements the distinction of access rights:

    $access=($user eq ‘流云‘?‘root’:‘guest‘);

The order operator (,) is not strictly a logical operator because it does not check the authenticity of the operands. Perl
The comma operator is computed from left to right, and the rightmost operand is returned, and the good operator is the continuation from C, which is used to
In reference to the use of C, I am not tired of the statement here.

2.5-character operator

Since Perl itself is developed for text processing., it adds many new string operators. The characters of Perl
The string operators include:

    . Character join operator
    x string copy operator
    =~ bind a variable to a pattern match
    !~ bind a variable to a pattern match, take a non

The first two operators are simpler. Now take a look at the example:

    Print ‘C‘.‘a‘.’l‘x2; #output result will be: Call;

The latter two operators are primarily used for pattern matching, and there will be a specific explanation of pattern matching in the future, and here is not much to say, we
Take a look at their examples to see how they work:

    $text=‘It’s raining today’;
    Print ($text=~/It’s raining/)? ‘It’s raining today’: ‘No rain today’;

We see examples of whether the variables contain the strings we need.

2.6 Assignment operators

The assignment operator is similar to the assignment operator for C, and the following are the various assignment operators:

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

2.7 Lvalue

quantity. For example, you cannot assign a value to a string in a Perl command file, such as "Bob" =32 the phrase
is wrong! Because "Bob" is not a lvalue, but if you assign a value to $bob, such as $BOB=32, the
statement is correct! Because the variable $bob is a lvalue.
in Perl, any meaningful lvalue can represent only one entity. For example, the first statement below lists the
value of the table (that is, the value of the array), @color is a lvalue, the second statement,
assigns the value of the table to 3 scalar variables, and 3 variables are lvalue:

@ Color= ($r, $g, $b);
    ($r, $g, $b) [email protected]; When the

Perl assignment operator processes a table, it can not process the entire table, but only one or several
elements of the table:

@times [2,5,9]= (20,40,10);
The statement under
assigns the first 2 values of the table to two scalars, and the remainder to another table:

     ($arg 1, $arg 2, @reset) [email  protected];

2.8 table operator

Perl includes the following table operators, and C does not:

 , table constructor
     .. range operator
     x table copy operator

Before we introduce "scalar and array variables," We've designed the constructor (I think it's called a delimiter,
Easier to understand) the range operator we used to create the array subscript range too! However, please note that it is much more than this,
It can also be used as a range that returns a sequential integer from the left operand to the right operand, including the operands on both sides. Command File Pass
A continuous integer table is often created using the range operator:


So we create a table with a value of (0,1,2,3,4,5,6,7,8,9)
Table copy operator is a very interesting thing, let's look at an example:


This table has 9 elements, what is the value of (1,2,3,1,2,3,1,2,3)? Very convenient!! :)

2.9 File Operators

Perl greatly expands the file processing operator. Perl has at least 27 operators that can test a file without opening the file
, unfortunately, because Perl was originally a UNIX tool, the vast majority of operators are on our popular platform:
WIN9X/NT system is not available. But fortunately, not all. There are 4 operators absolutely available, and the function is good oh! That's it.
4 operators:

  -d Test file is not a directory;
     -e Test if the file exists;
     -s test file size;
     -w Test if the file is writable;

The first two operators return a Boolean value (that is, true or false), and the 3rd operator returns the size of the file, in bytes, as a return. Below is
How to use:

    if(-e ‘perl.exe‘)
print ‘File size is:‘-s‘perl.exe‘;
        print ‘Can\‘t find perl.exe\n‘;
    (-w ‘SomeFile‘)||die "Cannot write to SomeFile\n";

Introduction to Perl syntax

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