File read and Write learning notes in Perl _perl

Source: Internet
Author: User
Tags perl interpreter readable

First, open, close the file

Syntax is open (Filevar, filename), where Filevar is a file handle, or the program used to represent a file code name, filename is filename, its path can be relative path, can also be absolute path.

Copy Code code as follows:

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

You must decide the access mode when you open the file, and there are three modes of access in Perl: Read, Write, and Add. The difference between the latter two modes is that the original file is covered by the write mode, the original content is lost, in the form of open (outfile, ">outfile"), while the Add mode continues to add the content at the end of the original file, in the form of open (AppendFile, ">> AppendFile "). Note that you cannot read and write/Add to a file at the same time.
The return value of open is used to determine whether the operation that opened the file succeeds, returns a value other than 0 when it succeeds, and returns zero when it fails, so it can be judged as follows:
Copy Code code as follows:

if (Open (MYFILE, "MYFILE")) {
# Here's what to do if the file opened successfully
}

End program when File open fails:
Copy Code code as follows:

Unless (open (MYFILE, "File1")) {
Die ("Cannot open input file file1\n");
}

You can also use logical OR operator notation as follows:
Copy Code code as follows:

Open (MYFILE, "File1") | | Die ("Could not open file");

When the file operation is finished, use Close (MYFILE); Closes the file.

Second, read the document

Statement $line =<>, reading a row of data from a file to a simple variable $line and moving the file pointer back one line. For standard input files, usually keyboard input, do not need to be opened. The statement @array = <>; reads the entire contents of the file into an array @array, and each line of the file (including a carriage return) is an element of @array.

Third, write the document

The form is:

Copy Code code as follows:

Open (outfile, ">outfile");
Print outfile ("Here's an output line.\n");

Note: STDOUT, stderr are standard output and standard error files, usually screen, and do not need to be opened.

Iv. Judging the status of documents
1. File test operator
The syntax is:-op expr, such as:

Copy Code code as follows:

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

File test operator
Operator description
-B is a block device
-C is a character device
-D is a directory
-E is present
Whether-f is a normal file
-G Whether the setgid bit is set
-K Whether the sticky bit is set
-L is a symbolic link
Whether-O owns the file
-P is a pipe
-R is readable
-S is not null
-T indicates whether the terminal
-U set the setuid bit
Whether-W can be written
-X is executable
-Z is an empty file
How long is the-a distance from last access
-B is a binary file
-C How long is the inode from the last Access file
-M distance last modified how long
Whether-O is owned only by the "True user"
-R is only "true user" readable
-S is a socket
-T is a text file
-W is only "real user" writable
-X is only "real user" executable
Note: "Real user" refers to the UserID specified at logon, which, in contrast to the current process user ID, commands suid can change the valid user ID. Cases:
Copy Code code 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 Code code as follows:

Open (INFILE, "INFILE") &&! (-E "outfile") &&
Open (outfile, ">outfile") | | Die ("Cannot open files\n");

V. Explanation of command Line parameters
like C, Perl also has array @argv that store command-line arguments, which can be used to handle individual command-line arguments; unlike C, $ARGV [0] is the first argument, not the program name itself.

Copy Code code as follows:

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

In Perl, an operator is actually an implied reference to an array of @argv that works:
1. When the Perl interpreter first sees it, open the file with $argv[0] as the filename;
2, carry out action shift (@ARGV); That is, the elements that @argv the array are moved forward one, and the number of elements is reduced by one.
3, the operator reads all the rows in the file opened in the first step.
4, after reading, the interpreter returned to the first step repeat.
Cases:
Copy Code code as follows:

@ARGV = ("Myfile1", "myfile2"); #实际上由命令行参数赋值
while ($line =) {
Print ($line);
}

The contents of the file Myfile1 and Myfile2 will be printed out.

Parameters of the function

Copy Code code as follows:

&ABC ("A", "B")
Sub ABC {
$first =$_[0];
$second =$_[1];
....
}

ABC ("A", "B")

The ABC function has a,b two parameters
The value of $_[0] is a
The value of $_[1] is B.
You can do this to deepen your understanding.

Copy Code code as follows:

&ABC ("A", "B")
Sub ABC {
$first =$_[0];
$second =$_[1];
Print $first. $second;
}

$_[0] Represents the first argument of a function
$_[1] Represents the second argument of a function
And so on .....
Copy Code code as follows:

#!/usr/bin/perl
$sum 1 = my_sum1 (1,2);
$sum 2 = my_sum2 (1,2);
print "sum1 = $sum 1 sum2 = $sum 2";
Sub My_sum1 {
($first, $second) =@_;
Return ($first + $second);
}
Sub My_sum2 {
$first =$_[0];
$second =$_[1];
Return ($first + $second);
}
Exit

++++++++++++++++++
Perl's expression is very flexible, the above two functions are equivalent, there are other methods, there are not many examples, the implementation of the results are:
Copy Code code as follows:

SUM1 = 3 Sum2 = 3

The first is more common, the second is a straightforward way of writing, 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 No. 999 parameter, while the others do not. In Perl, when a custom function receives an argument, it is placed in an array @_, $_[0],$_[1] is the argument from the array.

As a matter of fact, all the parameters for the incoming Perl process are passed in @_ identity. If you call a function with two arguments, they can be accessed within the function as the first two members of the @_ array: $_ [0] and $_[1]. Because @_ is just an ordinary array with strange names, you can handle it as you would a normal array, knowing this, and other writing patterns are not surprising:
For example: ($first, $second) =@_; is to pay the two elements in the array @_, respectively, to $first, $second, because @_ is an array, it is $first, $second parentheses to denote the list environment.

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

$& is used to hold the value in the match
$ ' used to hold all previous characters in match
$ ' used to store all characters after match

Such as:

Copy Code code as follows:

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

The results of the execution are:
Copy Code code as follows:

That actually matched ' there, '.
Hello Good
Neigbor Hello

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

Other commonly used variable @_
@_ is a private variable of a subroutine; if there is a global variable @_, it will be stored before the subroutine call, and when the subroutine call completes, its early values are returned to the @_. This means that when you pass a parameter to a subroutine, you don't have to worry about it affecting the value of the variable @_ the other subroutine in the program. When nested subroutine calls, the value of the @_ is similar to the above. Even when this subroutine is called recursively, each call gets a new @_, so the subroutine calls it gets its own argument list.

Unless the calling subroutine has a & followed by no parentheses (or no arguments), @_ is obtained from this caller's context. This is usually not a good idea, but it is sometimes useful.

Six, open the pipeline

You can also open and use Pipelines (ex:ls>tempfile) as a command line in the form of a program. such as statement open (Mypipe, "| Cat >hello "); Opens a pipe, and the output sent to mypipe becomes the input of the command "cat >hello". Because the cat command will display the contents of the input file, the statement is equivalent to open (Mypipe, ">hello"); Send the message by pipeline as follows:

Copy Code code as follows:

Open (Message, "| Mail Dave ");
Print message ("Hi, dave! Your Perl program sent this!\n ");
Close (message);

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.