13.2. Renaming a File

In the UNIX shell, you change the name of a file with the mv command. With Perl, the same operation is denoted with rename($old,$new). Here's how to change the file named fred into barney:

rename("fred","barney") || die "Can't rename fred to barney: $!";

Like most other functions, rename returns a true value if successful, so test this result to see whether the rename has indeed worked.

The mv command performs a little behind-the-scenes magic to create a full pathname when you say mv file some-directory. However, the rename function cannot. The equivalent Perl operation is:

rename("file","some-directory/file");

Note that in Perl we had to say the name of the file within the new directory explicitly. Also, the mv command copies the file when the file is renamed from one mounted device to another (if you have one of the better operating systems). The rename function isn't as smart, so you'll get an error, indicating you have to move it around some other way (perhaps by invoking a mv command on the same names). The File::Copy module supports a move function.

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.