Perl read/Write File Code instance
This article describes how to read and write file code instances in perl. This article provides the implementation code directly. For more information, see
# Mode operand create truncate
# Read <
# Write> yes
# Append> yes
Case 1: Throw an exception if you cannot open the file:
The Code is as follows:
Use strict;
Use warnings;
My $ filename = 'data.txt ';
Open (my $ fh, '<: encoding (UTF-8)', $ filename)
Or die "cocould not open file '$ filename' with the error $! ";
While (my $ row = <$ fh> ){
Chomp $ row;
Print "$ row \ n ";
}
Close ($ fh );
Case 2: Give a warning if you cannot open the file, but keep running:
The Code is as follows:
Use strict;
Use warnings;
My $ filename = 'data.txt ';
If (open (my $ fh, '<: encoding (UTF-8)', $ filename )){
While (my $ row = <$ fh> ){
Chomp $ row;
Print "$ row \ n ";
}
Close ($ fh );
} Else {
Warn "cocould not open file '$ filename' $! ";
}
Case 3: Read one file into array
The Code is as follows:
Use strict;
Use warnings;
My $ filename = 'data.txt ';
Open (FILEIN, "<", $ filename)
Or die "cocould not open file '$ filename' with the error $! ";
My @ FileContents = ;
For my $ l (@ FileContents ){
Print "$ l \ n ";
}
Close FILEIN;