SoFunction
Updated on 2025-04-07

Perl Concise Tutorial Perl Tutorial Collection

refer to:http://shouce./perl5/
Website environment configuration:https:///article/

Basic syntax of Perlhttps:///shouce/

Preface: What is perl and what is it for? Perl's original designer's intention was to process characters. 80% of its strengths were to process characters, and of course many others were OK. Many web pages now also use perl, and usually require a CGI environment, such as $char =~ /language/, which means to find strings containing the word "language". It can also do unix and linux system management, file content processing (based on the functions of tools such as awk and sed), and many other things you want to do.

1. Perl environment configuration

1. Get perl
Perl is usually located in /usr/local/bin/perl or /usr/bin/perl. You can get it for free on the Internet with anonymous FTP, such as ftp:///pub/gnu/perl-5.

2. The installation process is:
(1) Unzip:
      $gunzip perl-5.
      $tar xvf - <perl-5.
(2) Compilation:
      $make makefile
(3) Placement:
Copy the compiled executable file to the directory where the executable file is usually located, such as:
      $copy <compiled excutable file> /usr/local/bin/perl

3. Run
Edit your Perl program with a text editor, add the executable attribute: $chmod +x <program> and execute: $./<program>. If the system prompts: "/usr/local/bin/perl not found", it means that you have not installed successfully, please reinstall.
Note: The first line of your program must be #!/usr/local/bin/perl (where perl is located).

4 comments:
The comment method is to use the character # at the beginning of the statement, such as:
      # this line is a comment
Note: It is recommended to use comments frequently to make your program readable, which is a good programming habit.

2. Constant, variable and other issues

1. Single and double quotes
Simple variable replacement is supported in strings in double quotes, such as: $text = "This text contains the number $number.";
Escape characters are supported in strings in double quotes
There are two differences between single quoted strings and double quoted strings. One is that there is no variable replacement function, and the other is that the backslash does not support escape characters.
2. Repeat and link
Repeat: print "t" x 5 (5 ts will be output, note: where x is lowercase x in English letters)
Connection: $a.="bc"    (equivalent to)
3. Simple variables, arrays, lists
Simple variable: declare with $, such as: $a="hello";
Array: declared with @, such as: @arr=('a','b','c');
List: List is the value of a sequence contained in brackets. It can be any numerical value or empty, such as: (1, 5.3, "hello" , 2), empty list: ()

3. File operation

1. Open the file: such as open (MYFILE, "file1") || die ("Could not open file"); MYFILE is the declared file handle, file1 is the file name/file path, the whole line of code means: If the opening fails, output "Could not open file";
Close file: When the file operation is completed, close(MYFILE); to close the file.
2. Read the file
Statement $line = <MYFILE>; Read a line of data from the file and store it into the simple variable $line and move the file pointer back one line. <STDIN> is a standard input file, usually a keyboard input and does not need to be opened.
Statement @array = <MYFILE>; Read all the contents of the file into the array @array, and each line of the file (including the carriage return character) is an element of @array.

#!/usr/bin/perl
open(MYFILE,'');
@arr = <MYFILE>;
print @arr;

3. Write a file
The form is:
     open(OUTFILE, ">outfile");
     print OUTFILE ("Here is an output line.\n");
Note: STDOUT and STDERR are standard output and standard error files, usually screens and do not need to be opened.
4. Determine the file status

1. File test operator
The syntax is: -op expr, such as:
    if (-e "/path/file1") {
    print STDERR ("File file1 exists.\n");
    }

File test operator

Operator describe
-b Is it a block device?
-c Is it a character device?
-d Is it a directory?
-e Does it exist
-f Is it a normal file?
-g Is the setgid bit set?
-k Is the sticky bit set
-l Is it a symbolic link?
-o Whether to own the file
-p Is it a pipeline?
-r Is it readable
-s Is it not empty
-t Does it mean the terminal
-u Is the setuid bit set
-w Is it possible to write
-x Is it possible to execute
-z Is it an empty file?
-A How long has it been since the last visit
-B Is it a binary file?
-C How long does it take to last file access inode
-M How long has it been last modified
-O Is it only owned by "real users"
-R Is it only available for "real users" to read
-S Is it a socket?
-T Is it a text file?
-W Is there only "real users" to write
-X Is it possible to execute only "real users"
Note: "Real user" refers to the userid specified when logging in. It is opposite to the current process user ID. The command suid can change the valid user ID.

Example:
    unless (open(INFILE, "infile")) {
    die ("Input file infile cannot be opened.\n");
    }
    if (-e "outfile") {
    die ("Output file outfile already exists.\n");
    }
    unless (open(OUTFILE, ">outfile")) {
    die ("Output file outfile cannot be opened.\n");
    }
Equivalent to
    open(INFILE, "infile") && !(-e "outfile") &&
    open(OUTFILE, ">outfile") || die("Cannot open files\n");


4. Pattern matching:

1. Concept: Pattern refers to characters of a specific sequence found in a string, and is composed of the backslash: /def/, that is, pattern def. Its usage is like combining the function split to divide a string into multiple words in a certain pattern: @array = split(/ /, $line);
2. Match operator =~,!~
=~ Check whether the match is successful: $result = $var =~ /abc/; If the pattern is found in the string, a non-zero value is returned, that is, true, and if it does not match, it returns 0, that is, false. !~The opposite is true.

V. Control structure
(1) Conditional judgment: if()elseif()else();
(2) Loop:
1. While loop
2. Until loop
3. For loop
4. Foreach loop for each element of the list (array)

open(MYFILE,'');
@arr = <MYFILE>;
foreach $str (@arr){
 print $str;
}

5. Do loop
6. Loop control: Exit the loop as last, which has the same effect as break in C; execute the next loop as next, which has the same effect as continue in C; a command unique to PERL is redo, which means repeating this loop, that is, the loop variable remains unchanged and returns to the start point of the loop, but be careful that the redo command does not work in the do loop.
7. Traditional goto statement: goto label;
(3) Single line conditions
The syntax is statement keyword condexpr. where keyword can be if, unless, while or until, such as:
    print ("This is zero.\n") if ($var == 0);
    print ("This is zero.\n") unless ($var != 0);
    print ("Not zero yet.\n") while ($var-- > 0);
    print ("Not zero yet.\n") until ($var-- == 0);
Although the conditional judgment is written later, it is executed first.

6. Subprogram
(1) Definition
A subroutine is a separate piece of code that performs a special task. It can reduce duplicate code and make the program readable. In PERL, subroutines can appear anywhere in the program. The definition method is:
sub subroutine{
statements;
}
(2) Call
The call method is as follows: Call with &
       &subname;
       ...
       sub subname{
          ...
       }
7. File system: Closely related to Unix, reference:http://shouce./perl5/

OTHER:
Pipeline: The result of the previous execution can be used as the following parameters, such as
env | grep EDITOR
You can delete the value of EDITOR in the environment variable