in reply to Re: copy isn't working
in thread copy isn't working

Update 1: I am using WindowsOS. \\ worked for rename so using the same for copy as well.

Update 2: I did try with or die "Copy failed: $!" but returned "Copy failed: at c:\perl_scripts\copy_rename.pl line 33."

Update 3: I want to archive the file in a different directory with timestamp after processing it. Hope that helps

Code :

use strict; use warnings; use Time::Piece; use File::Copy; my $toDate = localtime->strftime('%F %T'); foreach my $file (glob "C:\\data\\app\\AppSpecific1\\In\\test*") { my $archiveFileName = $file."_".$toDate.".txt"; print "copy $file, $archiveFileName\n"; copy ($file, "C:\\data\\app\\AppSpecific1\\Archive\\".$archiveFile +Name) or die "Copy failed: $!"; }

Compilation error perl c:\perl_scripts\copy_rename.pl copy C:\data\app\AppSpecific1\In\test.txt, C:\data\app\AppSpecific1\In\test.txt_2019-03-07 12:22:44.txt Copy failed: at c:\perl_scripts\copy_rename.pl line 33.

Replies are listed 'Best First'.
Re^3: copy isn't working
by poj (Abbot) on Mar 07, 2019 at 17:39 UTC
    C:\data\app\AppSpecific1\In\test.txt_2019-03-07 12:22:44.txt

    Windows file names cannot contain colons :. Try using

    my $toDate = localtime->strftime('%Y-%m-%d_%H%M%S'); poj

      I tried both these options but didn't work.

      my $toDate = localtime->strftime('%Y-%m-%d_%H%M%S');

      my $toDate = localtime->strftime('%Y-%m-%d_%H_%M_%S');

        glob returns full path so $archiveFileName will include the directory.

        my $archiveFileName = $file."_".$toDate.".txt";

        and in the copy here you are adding the archive directory on to it

        print "copy $file, $archiveFileName\n"; copy ($file, "C:\\data\\app\\AppSpecific1\\Archive\\".$archiveFileName +) or die "Copy failed: $!";

        It might be easier to use readdir. For example

        #!perl use strict; use warnings; use Time::Piece; use File::Copy; my $toDate = localtime->strftime('%Y-%m-%d_%H%M%S'); my $dir = 'C:/data/app/AppSpecific1/In'; my $archiveDir = 'C:/data/app/AppSpecific1/archive'; opendir (my $dh, $dir) or die "Can't opendir $dir: $!"; while (my $file = readdir $dh) { next unless $file =~ /^test/; # filter as reqd my $srcFile = "$dir/$file"; next unless -f $srcFile; my $destFile = $archiveDir.'/'.$toDate.'_'.$file; print "copy $srcFile, $destFile\n"; copy ( $srcFile, $destFile) or die "Copy failed '$srcFile' to '$destFile' : $!"; } closedir $dh;

        Using the same variable in the print and the copy wil help debugging

        poj
        Space is a valid character in windows long filenames, but names containing spaces often require special quoting. I would at least consider using a regex to modify your time stamp to satisfy your requirements without violating window's constraints.
        Bill