CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
copy a file with a different name.

 



ianilkumar
Novice

Sep 10, 2012, 11:15 AM

Post #1 of 3 (899 views)
copy a file with a different name. Can't Post

Iam trying to copy a file with a different name by adding the date time stamp to it. But it doesn't work.

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

my $file_extension=`date "+%Y%m%d%H%M%S"`;
chomp $file_extension;
copy ("${PIN_HOME}/sys/data/pricing/example/pin_usage_map","${PIN_HOME}/sys/data/pricing/example/pin_usage_map.$file_extension");


looks like file_extension becomes empty when passed to copy function. How to fix it?


wickedxter
User

Sep 10, 2012, 6:44 PM

Post #2 of 3 (894 views)
Re: [ianilkumar] copy a file with a different name. [In reply to] Can't Post

are u sure $file_extension isn't undef. i think the " might be interfering with the back ticks `


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

my $file_extension=`date +%Y%m%d%H%M%S`;
chomp $file_extension;

copy ("${PIN_HOME}/sys/data/pricing/example/pin_usage_map",
"${PIN_HOME}/sys/data/pricing/example/pin_usage_map.$file_extension") or die("Copy failed, either first file doesn't exist or something else happend.");



FishMonger
Veteran / Moderator

Sep 11, 2012, 6:44 AM

Post #3 of 3 (884 views)
Re: [ianilkumar] copy a file with a different name. [In reply to] Can't Post

1) Instead of shelling out to the date command, it would be better to use the strftime function from the POSIX module.

2) $PIN_HOME was never assigned a value.

3) You should always use the strict and warnings pragmas. They would have told to about the problem with $PIN_HOME.

4) You should verify that the copy completed successfully and output a proper error message if it didn't.


Code
#!/usr/bin/perl 

use strict;
use warnings;
use POSIX qw(strftime);
use File::Copy;

my $ext = strftime("Y%m%d%H%M%S", localtime);
my $pin_home = '/home/user';
my $src_file = "$pin_home/sys/data/pricing/example/pin_usage_map";
my $new_file = "$pin_home/sys/data/pricing/example/pin_usage_map.$ext";

copy($src_file, $new_file) or die ("failed to copy '$src_file' to '$new_file' <$!>");



(This post was edited by FishMonger on Sep 11, 2012, 6:45 AM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives