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; |