Nov 082013
 
Article Perl

There is always more than one way to do things in Perl.

In this post some  of the possible ways to perform basic file handling operations are presented: renaming, moving to a different directory and making a copy of a file.

Renaming a file

Many of the file handling operations can be performed in Perl making a call to the corresponding command from the operating system. For instance, to rename a file “data.txt” to “data.csv” in a Linux system, a call to the ‘mv’ command can be made using the “backticks” syntax:

But it is generally advisable to make use of the equivalent perl built-in function, if it exists. In this case, the perl interpreter implements a “rename()” function to rename a file. For instance:

Calling a built-in function avoids the overhead incurred in the creation of a subprocess to execute an operating system command.

Moving a file

The “rename” built-in function can also be used to move a file to a different directory, as happens with the “mv” command:

But WARNING! this function does not allow to move a file to a different filesystem or disk.

Alternatively, to avoid this issue, the methods “move” or “mv” implemented in the module “File::Copy” can be used. Both are able to move a file to a different filsystem or disk, by first making a copy, and then deleting the original file. The different between them is in that “move” creates the new file with default permissions, and “mv” copies the permissions granted to the original file.

For instance, if we have two files “data.txt” and “data2.txt”, both with read/write permission granted only to the owner:

We can use the sample code below to move both files to a different filesystem mounted on “/disk2”, using “move” and “mv”:

and the result obtained is:

We can see that “/disk2/data2.txt” keeps the same permissions as the original file, but “/disk2/data.txt”  has default permissions.

Copying a file

There is no built-in function in perl to make a copy of a file. Instead, the File::Copy module implements several methods to perform this operation:

  • copy, cp – Both methos copy and cp work like the move and mv methods, in that copy creates a new file with default permissions, and cp preserves the permissions assigned to the original file
  • syscopy – syscopy is intended to make an exact copy of the original file, preserving all the attributes specific to different operating systems. For instance, on a Windows system, the call to syscopy is equivalent to a call to Win32::CopyFile from the Windows API.

References

Index of posts related to Perl programming

 Posted by at 9:10 am

 Leave a Reply

(required)

(required)