Contents Perl File copy

PERL - Copying Files

We can duplicate a file using the copy function. Copy takes two values the URL of the file to be copied and the URL of the new file. Since we want to duplicate the file in this example, we won't change the directory path but instead, just give the file a new name. If we used the same file name or the same URL, PERL will rewrite over the file if permissions allow.

We also must use a new module, the copy module of course.

PERL Code:

#!/usr/bin/perl
use File::Copy;

print "content-type: text/html \n\n"; #The header
$filetobecopied = "myhtml.html.";
$newfile = "myhtml.html.";
copy($filetobecopied, $newfile) or die "File cannot be copied.";

Here, we have simply duplicated the "myhtml.html" file and will be using it in further examples.

If we wanted to copy the file to a new directory, we can edit our variables to match the directory we wish to copy the file to.

PERL Code:

#!/usr/bin/perl
use File::Copy;

print "content-type: text/html \n\n"; #The header
$filetobecopied = "myhtml.html.";
$newfile = "html/myhtml.html.";
copy($filetobecopied, $newfile) or die "File cannot be copied.";

Now we have copied the file from its current directory to an HTML directory.

When using PERL on the web, it is best to use complete internet URL. We used a shorthand way in the example but a better solution may be to hardcode the full URL meaning; http://www.your.com/myhtml.html.

PERL - Moving Files

Moving a file requires the use of the move function. This functions works exactly as the copy function from above and we send PERL the same module. The difference is that instead of copying we are 'cutting' the file and sending it to a new location. It works the same as cutting and pasting text from an office document to another.

PERL Code:

#!/usr/bin/perl
use File::Copy;

print "content-type: text/html \n\n"; #The header
$oldlocation = "myhtml.html";
$newlocation = "html/myhtml.html";
move($oldlocation, $newlocation);

Now our file has been completly removed from its current location and placed into the new location.

Want Some more information and Video ???

Home