By Bryan Young
Expert Author
Article Date: 2010-08-10
An important aspect of Perl is it's ability to read from and write to files in the filesystem. Without this ability, it would be a lot harder to create log files or run search/replace scripts on your files, since there are few other languages that can even come close to Perl's ability to do so.
An important aspect of Perl is it's ability to read from and write to files in the filesystem. Without this ability, it would be a lot harder to create log files or run search/replace scripts on your files, since there are few other languages that can even come close to Perl's ability to do so.
The first function you need to know when dealing with files in Perl is open(). This is used to open the file and store the filehandler to a variable you can use to access said file. The open() function is used as such.
open(FILEHANDLER, "file.txt");
The first argument is the filehandler you use to access the file you just opened, myfile.txt. You can open your file with a specific goal in mind by using certain characters preceding the file name.
open(READFILE, "<readme.txt");
open(WRITEFILE, ">outputfile.txt");
open(APPENDFILE, ">>logfile.txt");
As you can probably guess, using '<' will open a file read-only, '>' will open a file for writing, and '>>' will open a file and append any output to the end of the file. If no symbol is used, the file is opened read-only. If you open a file using an already defined filehandler, the old file will be automatically closed, and the new file opened.
Reading from a file is accomplished by using the <> operator. This can be used in two ways. Used with a string, <> will read one line of data (including the newline character at the end). Used with an array, <> will read in all lines (and newline characters) and place each line into its own element of that array.
$oneline = <READFILE>; #reads one line
@lines = <READFILE>; #each element is one line
In order to remove the newlines from the end of your output, use the chomp() function.
chomp($oneline);
chomp @lines;
Writing to a file is done using the same functions you are already familiar with, print and printf. The only difference is you include the filehandler as the first argument of the function.
print WRITEFILE "This is a line of output.n";
printf APPENDFILE "This is what you read in earlier: %sn", $oneline;