eading from a file in Perl is pretty simple. After all, the language is pretty much built around dealing with text. The first step is to open the file, in which case you just need to use the following:
open(INFILE,"< myfile.txt") or die "Can't open file: $!";
In this statement we are using the open() function with a filehandle and filename as arguments. We will use this filehandle for all further actions on the file. The rest of the statement will print the error “Can’t open file: $!” where $! is the filename, should the script be unable to open the file.
To read a file which already has an open filehandleyou can use the following:
while(<INFILE>){
print $_;
}
This while loop will read through the file line by line, printing the contents, until it reaches the last line where it will terminate. In Perl $_ is a special character. It represents the “default input and pattern matching space”, which in the context above means that each line of the file is assigned to $_ in turn as the file is being read. So when we use print $_ we are printing the current line, and with each iteratation of the loop that line changed to the next.