VOOZH about

URL: https://www.geeksforgeeks.org/perl/perl-writing-to-a-file/

⇱ Perl | Writing to a File - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Perl | Writing to a File

Last Updated : 7 Mar, 2019
A filehandle is a variable that is used to read and write to a file. This filehandle gets associated with the file. In order to write to the file, it is opened in write mode as shown below:
open (FH, β€˜>’, β€œfilename.txt”);
If the file is existing then it truncates the old content of file with the new content. Otherwise a new file will be created and content will be added.
print() function
print() function is used to write content to a file.
Syntax: print filehandle string
Here, filehandle is associated to the file at the time of opening the file and string holds the content to be written to the file. Example : Before Writing to File: πŸ‘ Image
Executing Code to Write: πŸ‘ Image
Updated File: πŸ‘ Image
Here is how the program works: Step 1: Opening file Hello.txt in write mode. Step 2: Getting the text from the standard input keyboard. Step 3: Writing the string stored in '$a' to the file pointed by filehandle 'fh' Step 4: Closing the file.   Copying Content from one file to another: Before Code Execution: Source File: πŸ‘ Image
Destination File: πŸ‘ Image
Example : Example below reads the content from the source file and writes it to destination file. Executing Code: πŸ‘ Image
Updated Destination File: πŸ‘ Image
Here is how the program works:- Step 1: Opening 2 files Source.txt in read mode and Destination.txt in write mode. Step 2: Reading the content from the FHR which is filehandle to read content while FHW is a filehandle to write content to file. Step 3: Copying the content with the use of print function. Step 4: Close the conn once reading file is done.  
Error Handling and Error Reporting
There are two ways in which Errors can be handled
  • Throw an exception if file cannot be opened (Handling an error)
  • Give a warning if file cannot be opened and continue running (Error reporting)
Throw an Exception (Using Die Function) When filehandle could not be assigned a valid file pointer at that time die gets executed printing the message and kills the current program. Example : πŸ‘ Image
In the above code when File exists it simply gets executed with no errors but if file doesn't exists then it generates an error and code terminates. Give a warning (Using warn function) When filehandle could not be assigned a valid file pointer it just prints warning message using warn function and keeps running. Example : When File exists: πŸ‘ Image
When File doesn't exists: πŸ‘ Image
Comment
Article Tags:
Article Tags:

Explore