kiwi_bris_ct has asked for the wisdom of the Perl Monks concerning the following question:

Please find my code as follows. I am trying to insert the day before date into the filename. Can anyone help.
my $yesterday = get_date (-1); print "Yesterday = $yesterday\n"; sub get_date { my $offset = shift || 0; my $ts = time + $offset*60*60*24; my ($day,$month,$year) = (localtime($ts))[3,4,5]; sprintf ("%02s%02s%04s",$day,$month+1,$year+1900); } rename "d:/EOD/20 January 2002/system.csv", "d:/EOD/20 January 2002/?? +???_system.csv"; rename "d:/EOD/20 January 2002/sales.csv", "d:/EOD/20 January 2002/??? +??_sales.csv"; my $source = "d:/EOD/20 January 2002/?????_system.csv"; my $source1 = "d:/EOD/20 January 2002/?????_sales.csv"; my $destination = "c:/New EOD/?????_system.csv"; my $destination1 = "c:/New EOD/?????_sales.csv"; open IN, $source or die "Can't read source file $source: $!\n"; + open IN, $source1 or die "Can't read source file $source1: $!\n"; + open OUT,">$destination" or die "Can't write on file $destination: $!\ +n"; open OUT,">$destination1" or die "Can't write on file $destination1: $ +!\n"; print 'Renamed csv files with date and copied to new directory'; while (<IN>) { print OUT $_; }

Replies are listed 'Best First'.
Re: Renaming file with date
by perlplexer (Hermit) on Apr 23, 2002 at 12:51 UTC
    You are opening two files using the same file handle; so, the second open() closes previously open file. In addition, you are wiping out the contents of file referenced by $destination.

    Don't write your own code for copying files unless you have to.
    Use File::Copy instead. strftime() from POSIX will help you format date strings.
    use strict; use File::Copy; use POSIX; my @files = ('system.csv', 'sales.csv'); # your files my $home = 'd:/EOD/20 January 2002/'; # source my $archive = 'c:/New EOD/'; # destination # the day before my $yesterday = strftime("%Y%m%d", localtime(time - 24*60*60)); # copy all files from $home to $archive; # prepend yesterday's date to all file names. for (@files){ copy $home.$_, "$archive${yesterday}_$_" or print "ERROR: Can't copy $_ : $!\n"; }
    --perlplexer
Re: Renaming file with date
by derby (Abbot) on Apr 23, 2002 at 12:25 UTC
    I'm not quite sure where you're having problems. Do you wish to replace the questions marks with some date part? If so, you have a great start with your get_date function. For the rest of the code, I would suggest you use File::Copy for the copying and Date::Manip for more complex date parsing.

    -derby

      Thank you for your help....I am still very new to perl. Thanks again...
Re: Renaming file with date (TMTOWT name files with date/time stamp)
by ybiC (Prior) on Apr 23, 2002 at 16:28 UTC
    Unless I misunderstand your question, brother kiwi_bris_ct, this thread should help, as it provides a variety of ways to name a file with the (date|time)stamp.
        cheers,
        Don
        striving toward Perl Adept
        (it's pronounced "why-bick")