Perl Learning (2) File Processing

Source: Internet
Author: User

1. Read an object. If the object does not exist, an error is reported and the error cause is displayed.

open (DB, "/home/ellie/myfile") or die "Can't open file: $!\n";  
After running, the system prompts: Can't open file: no such file or Director 2. how to read and write files:

Open (FH, "<FILENAME"); # opens "FILENAME" for reading. Read
# The <; symbol is optional.




Open (FH, "> FILENAME"); # opens "FILENAME" for writing. Write
# Creates or truncates file.




Open (FH, "> FILENAME"); # opens "FILENAME" for appending. append
# Creates or appends to file.



Open (FH, "+ <FILENAME"); # opens "FILENAME" for read, then write. Write after read
Open (FH, "+> FILENAME"); # opens "FILENAME" for write, then read. First write and then read



Close (FH );

3. Open and print the file
#!/usr/bin/perl

open(FH, "<d:/readtest.txt") or die "Can't open file: $!\n";
while(<FH>){ print }

4. File Attributes

#! /Usr/bin/perl




My $ file = "D:/readtest.txt ";



# Is it readble, writeable, and executable?
Print "file is readable, writeable, and executable \ n" If-r $ file and-W _ and-X _;



# When was it last modified?
Print "file was last modified",-M $ file, "days ago. \ n ";



# Print a directory
Print "file is a directory. \ n" If-d $ file; # Is it a directory?

Because this file actually exists and is just created, but it is only a common text file, the final result is file was last modified 0.0239930555555556 days ago. if the code is print "file is readable, writeable, and executable \ n" If-r $ file and-W _ and-X _; is changed to: Print "file is readable, writeable, and executable \ n "If-r $ file and-W _; the final result is:

File is readable, writeable, and executable

File was last modified 0.0251851851851852 days ago.

 

-W _ is short for-W $ file.

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.