SoFunction
Updated on 2025-04-07

Two implementation methods for Perl to read strings from files

1. Read all the contents in the file into an array at once (this method is suitable for small files):
 

Copy the codeThe code is as follows:
open(FILE,"filename")||die"can not open the file: $!";
@filelist=<FILE>;

foreach $eachline (@filelist) {
        chomp $eachline;
}
close FILE;
@filelist=<FILE>;

When the file is large, an "out of memory" error may occur.

2. Read one line from the file at a time, read and process it one line at a time (it is more convenient to read a large file):
 

Copy the codeThe code is as follows:

open(FILE,"filename")||die"can not open the file: $!";
while (defined ($eachline =<FILE>)) {
     chomp $eachline;
         # do what u want here!
}
close FILE;