Wednesday, March 18, 2020
How to Read and Write Files in Perl
How to Read and Write Files in Perl Perl is an ideal language for working with files. It has the basic capability of any shell script and advanced tools, such as regular expressions, that make it useful. In order to work with Perl files, you first need to learn how to read and write to them. Reading a file is done in Perl by opening a filehandle to a specific resource. Reading a File in Perl In order to work with the example in this article, youll need a file for the Perl script to read. Create a new text document calledà data.txtà and place it in the same directory as the Perl program below. In the file itself, just type in a few names - one per line: When you run the script, the output should be the same as the file itself. The script is simply opening the specified file and looping through it line by line, printing each line as it goes. Next, create a filehandle called MYFILE, open it, and point it at theà data.txt file. Then use a simple while loop to automatically read each line of the data file one at a time. This places the value of each line in the temporary variable $_ for one loop. Inside the loop, use the chomp function to clear off the newlines from the end of each line and then print the value of $_ to show that it was read. Finally, close the filehandle to finish out the program. Writing to a File in Perl Take the same data file you worked with while learning to read a file in Perl. This time, you will write to it. To write to a file in Perl, you must open a filehandle and point it at the file youre writing. If youre using Unix, Linux or a Mac, you might also need to double-check your file permissions to see if your Perl script is allowed to write to the data file. If you run this program and then run the program from the previous section on reading a file in Perl, youll see that it added one more name to the list. In fact, every time you run the program, it adds another Bob to the end of the file. This is happening because the file was opened inà appendà mode. To open a file in append mode, just prefix the filename with theà à symbol. This tells the open function that you want to write to the file by tacking more onto the end of it. Ifà instead,à you want to overwrite the existing file with a new one, you use theà à single greater than symbol to tell the open function that you want a fresh file each time. Try replacing the with a and you see that the data.txt file is cut down to a single name - Bob - each time you run the program. Next, use the print function to print the new name to the file. You print to a filehandle by following the print statement with the filehandle. Finally, close the filehandle to finish out the program.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.