How to backup files with timestamp in Perl?
Question
How to backup files with timestamp in Perl?
Backing up files with a timestamp in Perl is a common task in system administration. This approach appends a date/time string to the filename to avoid overwriting previous backups and to keep track of when each backup was made.
Here’s a comprehensive explanation and example showing how to copy a file and add a timestamp to the backup filename using core Perl features only.
Key concepts
localtime(): Perl’s built-in function to get the current date/time.- String formatting: constructing a timestamp string like
YYYYMMDD_HHMMSS. copyoperation: done either by reading/writing or using core modules likeFile::Copy.- Understanding
scalarvslistcontext (e.g., localtime gives a list of date/time components).
Simple example: Backing up a file with timestamp in filename
use strict;
use warnings;
use File::Copy; # Core module, no extra install needed
# Source file to backup
my $source_file = "example.txt";
# Get current timestamp in format YYYYMMDD_HHMMSS
my @t = localtime();
my $timestamp = sprintf("%04d%02d%02d_%02d%02d%02d",
$t[5] + 1900, $t[4] + 1, $t[3],
$t[2], $t[1], $t[0]);
# Construct backup filename by appending timestamp before extension
my $backup_file = $source_file;
if ($backup_file =~ /^(.*?)(\.[^.]+)?$/) {
$backup_file = $1 . "_" . $timestamp . ($2 // '');
} else {
# fallback if no extension
$backup_file = $source_file . "_" . $timestamp;
}
# Copy the file
if (copy($source_file, $backup_file)) {
print "Backup successful: $backup_file\n";
} else {
warn "Failed to backup $source_file: $!\n";
}
Explanation
The code:
- Uses
localtime()in list context returning an array with date parts. Note the adjustments for year (1900 + $t[5]) and month (1 + $t[4]), as Perl’s months are zero-based and year is years since 1900. - Builds a timestamp string with
sprintfto zero-pad numbers properly. - Splits the original filename into base and extension using a regex, then inserts the timestamp before the extension.
- Uses
File::Copy::copy()to make the file copy; this is a core module and the simplest way to copy files in Perl safely. - Prints a confirmation or warning depending on success.
Common pitfalls
- Be careful with the timestamp formatting—forgetting to add 1900 to the year or 1 to the month causes incorrect dates.
- For filenames without extensions, handle them differently so timestamp is just appended.
- Check file exists before copying in real scripts to avoid errors.
- Using plain filehandles to copy can be done but is error-prone—prefer
File::Copy. - Beware of filename characters that might interfere with shells if you use this in command execution.
Perl version notes
This example uses basic core Perl features available since early Perl 5 versions (for example, File::Copy has been core for decades). No modern features beyond Perl 5.8 are necessary here.
Using this method, you can efficiently maintain timestamped backups of files for reliable versioning and restore if needed.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 24ms
Backup successful: example_20251230_132643.txt
(empty)