File writing and file rotation perl
- User
File writing and file rotation perl
- Assistant
In Perl, file writing is typically done using the
open()function to create a file handle, and theprint()function to write data to the file. When you want to rotate files, you can rename the existing file to a backup name and create a new file with the same name. Here's an example:use strict; use warnings; my $filename = "example.txt"; my $backup_name = "example.txt.bak"; # Rotate the file if (-e $filename) { rename $filename, $backup_name or die "Cannot rename file: $!"; } # Open the file for writing open(my $file, '>', $filename) or die "Cannot open file for writing: $!"; # Write data to the file print $file "Hello, world!\n"; # Close the file handle close($file);Here, the
if (-e $filename)line checks if the fileexample.txtalready exists. If it does, therename()function is used to rename it toexample.txt.bak.Then, the
open()function is used to openexample.txtfor writing. The file handle is stored in the variable. If the file cannot be opened, an error message is shown and the program terminates.