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

Hi Monks,

I need help with this snippet of code :

my ($oldpath, $newpath, $line); open (WORKFILE, "c:\\temp\\work.txt"); while ($record = <WORKFILE>) { $oldpath = "c:\\olddir\\$record"; $newpath = "c:\\newdir\\$record"; rename("$oldpath", "$newpath"); } close(WORKFILE);

Basically, it is reading a text file containing lines of file names. As I read the list, I would like to move them to another directory but somehow, it doesn't seem to be working.

If I replace the "rename" with "print", the correct "oldpath" & "newpath" is displayed, which means that the variables have been correctly assigned and the path & file names are correct. But it just doesn't rename/move.

Am I doing something wrong?

Thanks !

Replies are listed 'Best First'.
Re: Not renaming/moving files
by toolic (Bishop) on Jan 27, 2010 at 01:05 UTC
    Try checking if the rename passed, and display an error message if it failed:
    rename("$oldpath", "$newpath") or die "Error: $!";
    Typically, the old file does not exist, or the new file can not be created because permissions are not set properly.

    Update: and try to chomp your $record.

    use strict; use warnings; open my $fh, '<', "c:\\temp\\work.txt" or die "can not open file: $!"; while (my $record = <$fh>) { chomp $record; my $oldpath = "c:\\olddir\\$record"; my $newpath = "c:\\newdir\\$record"; rename $oldpath => $newpath or die "Error: $!"; } close $fh;
Re: Not renaming/moving files
by Anonymous Monk on Jan 27, 2010 at 01:12 UTC
    chomp $record ?
      chomp removes the \n character from the string. If you read text data into perl, \n is not removed automatically.
Re: Not renaming/moving files
by ranciid (Novice) on Jan 28, 2010 at 07:57 UTC
    Hi all,

    Thanks for all your replies !

    "chomp"-ing works !!

    Thanks once again !!