File Operations for Perl learning notes

Source: Internet
Author: User

File Operations for Perl learning notes

This article mainly introduces the file operations of Perl learning notes. This article provides examples of opening files, reading files, and Writing File Code respectively. For more information, see

 

 

Perl's file operations are similar to other languages, that is, open, read, and write operations.
1. open the file

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

#! C:/perl/bin/perl-w

Use utf8;

Use strict;

Use warnings;

 

My $ filename = 'test.txt '; # or use an absolute path, for example, c:/perl/Learn/test.txt.

 

If (open (MYFILE, $ filename) # MYFILE is a flag

{

Printf "Can open this file: % s! ", $ Filename;

Close (MYFILE );

}

Else {

Print "Can't open this file! ";

}


2. Read files

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

#! C:/perl/bin/perl-w

Use utf8;

Use strict;

Use warnings;

 

My $ filename = 'test.txt ';

If (open (MYFILE, $ filename ))

{

My @ myfile = <MYFILE>; # To read multiple rows, use this method. If only one row is read: $ myfile = <>;

My $ count = 0; # number of rows to be read. The initial value is 0.

Printf "I have opened this file: % s \ n", $ filename;

While ($ count <@ myfile) {# traverse

Print ("$ myfile [$ count] \ n"); # Note this method.

$ Count ++;

}

Close (MYFILE );

}

Else {

Print "I can't open this file! ";

}

Exit;

3. Write files

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#! C:/perl/bin/perl-w

Use utf8;

Use strict;

Use warnings;

 

My $ filename = 'test.txt ';

 

If (open (MYFILE, ">". $ filename) # Add or not delete this write method.

{# Rewrite the file content MYFILE, ">". $ filename

Print MYFILE "Write File appending Test \ n ";

Close (MYFILE );

}

Else {

Print "I can't open this file! ";

}

Exit;

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.