O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required