file-io beginner

How to rename a file in Perl?

Question

How to rename a file in Perl?

Renaming a file in Perl is straightforward using the built-in rename function. This function attempts to rename or move a file (or directory) from one path to another. If successful, it returns true; otherwise, it returns false and sets the $! variable with the error.

Using rename in Perl

The syntax is:

rename old_filename, new_filename;

This attempts to rename the file old_filename to new_filename. It works across directories, so you can also use it to move a file within the filesystem.

Here are some important points about rename in Perl:

  • The rename function works at the OS system call level, so it will fail if you try to rename across different filesystems (e.g., from one mounted drive to another). For cross-filesystem moves, you'll need to manually copy and unlink the file.
  • rename returns true on success, or false on failure, setting $! with the reason.
  • You should always check the return value to handle errors.
  • On Windows, the semantics can be slightly different; for instance, renaming over an existing file might fail.

Example: Renaming a File

This example shows how to rename a file and handle potential errors gracefully.

use strict;
use warnings;

my $old_name = "old_file.txt";
my $new_name = "renamed_file.txt";

# Attempt to rename the file and check for success
if (rename $old_name, $new_name) {
    print "File successfully renamed from '$old_name' to '$new_name'.\n";
} else {
    print "Failed to rename file: $!\n";
}

Running this code will rename old_file.txt to renamed_file.txt if the file exists and you have the necessary permissions.

Perl Concepts Highlighted

  • rename is a built-in Perl function that interfaces with the OS.
  • $! is a special variable containing the last OS error.
  • Proper error checking after system calls is critical.
  • Perl’s context allows rename to be used directly in conditional statements for clean code.

Common Pitfalls

  • Trying to rename a non-existent file will fail.
  • Attempting to rename across file systems doesn't work and will return false.
  • Lack of permissions to modify the directory or file will cause failure.
  • On some platforms, renaming over an existing file may not overwrite it.

Using rename is the simplest approach to rename files in Perl, and with basic error handling, it works reliably for most use cases.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 5ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions