Learning Perl on Win32 Systems

Learning Perl on Win32 SystemsSearch this book
Previous: 13.1 Removing a FileChapter 13
File and Directory Manipulation
Next: 13.3 Making and Removing Directories
 

13.2 Renaming a File

In the command shell, you change the name of a file with the rename command. And so it is with Perl, too, where this 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, the rename function returns a true value if successful, so test this result to see whether the rename has indeed worked.

The rename function is perhaps more like the command-prompt move command than the command-prompt rename command. Perl's rename can move a file into a different directory, as can move.

The move command performs a little behind-the-scenes magic to create a full pathname when you say move 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. If you try to rename a file to a filename that already exists, rename will overwrite the existing file; this result is different than that of the Windows NT rename command, which will fail if the file already exists.


Previous: 13.1 Removing a FileLearning Perl on Win32 SystemsNext: 13.3 Making and Removing Directories
13.1 Removing a FileBook Index13.3 Making and Removing Directories