SoFunction
Updated on 2025-04-07

Read and write a study notes in file in Perl

1. Open and close the file

The syntax is open (filevar, filename), where filevar is a file handle, or the code used in the program to represent a file, filename is the file name, and its path can be a relative path or an absolute path.

Copy the codeThe code is as follows:

 open(FILE1,"file1");
 open(FILE1, "/u/jqpublic/file1");

When opening a file, you must decide on the access mode. There are three access modes in PERL: Read, Write, and Add. The difference between the latter two modes is that the write mode overwrites the original file and the original content is lost, the form is: open (outfile,">outfile"); while the addition mode continues to add content at the end of the original file, the form is: open(appendfile, ">>appendfile"). It should be noted that the file cannot be read and write/added at the same time.
The return value of open is used to determine whether the operation of opening a file is successful. When it succeeds, it returns a non-zero value and when it fails, it can be judged as follows:
Copy the codeThe code is as follows:

if (open(MYFILE, "myfile")) {
# here's what to do if the file opened successfully
}

End the program when the file is opened fails:
Copy the codeThe code is as follows:

unless (open (MYFILE, "file1")) {
 die ("cannot open input file file1\n");
}

It can also be represented by logic or operators as follows:
Copy the codeThe code is as follows:

 open (MYFILE, "file1") || die ("Could not open file");

When the file operation is completed, close(MYFILE); to close the file.

2. Read the file

Statement $line =<> ; Read a line of data from a file and store it into a simple variable $line and move the file pointer back one line. It is a standard input file, usually a keyboard input and does not need to be opened. The statement @array = <>; reads the entire content of the file into the array @array, and each line of the file (including the carriage return) is an element of @array.

3. Write a document

The form is:

Copy the codeThe code is as follows:

 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:

Copy the codeThe code is as follows:

if (-e "/path/file1") {
 print STDERR ("File file1 exists.\n");
}

File test operator
Operator Description
-b Is it a block device?
-c  Is it a character device
-d  Is it a directory
-e  Whether it exists
-f  Is it a normal file
-g  Whether the setgid bit is 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  Whether to represent the terminal
-u  Whether the setuid bit is set
-w  Is it possible to write
-x  Is it executable
-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 user" 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:
Copy the codeThe code is as follows:

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
Copy the codeThe code is as follows:

open(INFILE, "infile") && !(-e "outfile") &&
open(OUTFILE, ">outfile") || die("Cannot open files\n");

5. Interpretation of command line parameters
Like C, PERL also has an array @ARGV that stores command line parameters, which can be used to process each command line parameter separately; unlike C, $ARGV[0] is the first parameter, not the program name itself.

Copy the codeThe code is as follows:

$var = $ARGV[0]; # First parameter
$numargs = @ARGV; # Number of parameters

In Perl, operators are actually implicit references to the array @ARGV, which works as follows:
1. When the PERL interpreter first sees it, open a file with $ARGV[0] as the file name;
2. Execute the action shift(@ARGV); that is, move the element of the array @ARGV forward by one, and the number of elements is reduced by one.
3. The operator reads all lines in the file opened in the first step.
4. After reading, the interpreter returns to the first step and repeats it.
Example:
 
Copy the codeThe code is as follows:

@ARGV = ("myfile1", "myfile2"); #In fact, it is assigned by the command line parameter
 while ($line = ) {
  print ($line);
 }
 

Print out the contents of files myfile1 and myfile2.

Function parameters

Copy the codeThe code is as follows:

&abc("a","b")
  sub   abc   { 
  $first=$_[0]; 
  $second=$_[1]; 
  .... 
  }

abc("a","b") 

There are two parameters a and b in the abc function
The value of $_[0] is a
The value of $_[1] is b
This can deepen your understanding

Copy the codeThe code is as follows:

  &abc("a","b") 
  sub   abc   { 
   $first=$_[0]; 
   $second=$_[1]; 
  print   $first.$second; 
 }  

$_[0] represents the first parameter of the function
$_[1] represents the second parameter of the function
And so on...
Copy the codeThe code is as follows:

#!/usr/bin/perl 
  $sum1   =   my_sum1(1,2); 
  $sum2   =   my_sum2(1,2); 
  print   "sum1   =   $sum1         sum2   =   $sum2"; 
sub   my_sum1 { 
  ($first,$second)=@_; 
  return($first+$second); 
 }
sub   my_sum2   { 
 $first=$_[0]; 
 $second=$_[1]; 
 return($first+$second); 
  } 
exit; 

++++++++++++++++++ 
The expression of Perl is very flexible. The above two functions are equivalent. There are other writing methods. I won't give many examples here. The execution result is:
Copy the codeThe code is as follows:

  sum1 = 3  sum2  = 3 

The first method is relatively common, and the second method is a simple and direct method. You can only receive the parameters you want. The advantage is that if you receive 10,000 parameters, you can use $_[999] to receive the 999th parameter, and don’t worry about the others. In PERL, when a custom function receives parameters, it is placed in the array @_, $_[0], $_[1] is to get parameters from the array.

In fact, it is very simple. All parameters passing in perl process are passed in as @_. If a function with two arguments is called, they can be accessed inside the function as the first two members of the @_array: $_[0] and $_[1]. Because @_ is just an ordinary array with a strange name, you can handle it as casually as you work with a normal array. Knowing this, it is no surprise for other writing patterns:
For example: ($first,$second)=@_;   It means paying two elements in the array @_ to $first and $second respectively. Since @_ is an array, $first and $second are enclosed in brackets to represent the list environment.

What else is $first = shift; $second = shift; Pay the first element in @_ to $first and the second element to $second.
The special variables $&, $`,$' in Perl are used in pattern matching

$& is used to store the matching values
$`   Used to store all characters before the match
$'   Used to store all characters after the match

like:

Copy the codeThe code is as follows:

#!/usr/bin/perl -w
if("Hello good  there,neigbor hello" =~ /\S\w+,/){
 print "That actually matched '$&'. ";
 print $`." ";
 print $'." ";
}

The result of execution is:
Copy the codeThe code is as follows:

That actually matched 'there,'.
Hello good 
neigbor hello

---------------------------

Also commonly used variable @_
@_ is a private variable of the subroutine; if there is a global variable @_, it will be stored before this subroutine call, and when the subroutine call is completed, its early value will be reassigned to @_. This means that when passing the parameter to the subroutine, you don't have to worry about it affecting the value of @_ variable of other subroutines in this program. When a nested subroutine is called, the value of @_ is similar to the above. Even when this subroutine is called recursively, each call will get a new @_, so the subroutine will get its own parameter list when it is called.

Unless the called subroutine has & before and no brackets (or no parameters) after it, @_ is obtained from the context of this caller. This is usually not a good idea, but sometimes it is useful.

6. Open the pipeline

The use of the program can also open and use the pipeline (ex:ls>tempfile) like the command line. For example, the statement open (MYPIPE, "| cat >hello"); opens a pipeline and the output sent to MYPIPE becomes the input of the command "cat >hello". Since the cat command will display the contents of the input file, this statement is equivalent to open(MYPIPE, ">hello"); the email is sent through the pipeline as follows:

Copy the codeThe code is as follows:

 open (MESSAGE, "| mail dave");
 print MESSAGE ("Hi, Dave! Your Perl program sent this!\n");
close (MESSAGE);