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

Hello Monks, This program finds a file in a directory then it copies to another directory. it works find but I'm trying to rename the file after it finishes copying to the destination directory. The thing is that I read a file and grab the first field[0] which contains the "String" that rename the file (for example 123456.rtf), then I grab field13 which contains the path of the directory that I'm grabbing the file from (for example C:\abc\mydir) I'm not very familiar to do the rename procedure after copying the file. I could grab the file out the source directory but cannot rename after copying the file to destination directory because it only copies one file and doesn't continue reading the file. Do you have any ideas to accomplish this task? Here is my code
#! perl -w use strict; use File::Copy; my $infile = 'c:/doclist1.chr'; open IN, "<$infile" or die "Couldn't open $infile, $!"; while (<IN>) { chomp; my @fields = split /,/; my $mrn = $get_mrn[0]; my $path_str = $fields[13]; do { warn "Empty field 13"; next } unless $path_str; my @path = split /\\/, $path_str; my $dir = join "\\", @path[ 0, 5, 6 ]; process_dir($dir); } close IN; sub process_dir { my $dir = shift; do { warn "$dir does not exist!\n"; return } unless -e $dir; opendir DIR, $dir or do { warn "Could not open $dir $!\n" ; return }; while ( my $file = readdir DIR ) { next unless -f "$dir\\$file"; next unless $file =~ m/\.rtf$/; copy( "$dir\\$file", "C:\\testfiles\\$file" ) or die "Failed to copy $file: $!\n"; } }

Replies are listed 'Best First'.
Re: FindCopyRename File
by Zaxo (Archbishop) on May 30, 2003 at 02:53 UTC

    The File::Copy copy function allows you to give the copy a new name. Just say

    my $newname = make_newname( $file); copy( "$dir\\$file", "C:\\testfiles\\$newname" ) or die "Failed to copy $file: $!\n";
    with some suitable definition of sub make_newname.

    The rename function is not difficult to use, either. Syntax is rename OLDNAME, NEWNAME.

    After Compline,
    Zaxo