1

how can I do this mv ($file $new_file/$1) or die("Errors 2");

so it would stop the script in terminal if the file is not found?

otherwise it keeps repeating and repeating and I need to restart putty session so i would be able to type something

4
  • What is repeating? There's no loop here. Also, mv() is not a Perl function. The Perl function that renames a file is called rename(). Oct 7, 2011 at 17:56
  • the loop is around the function, so basically it does not move the correct file and thats why it keeps repeating, so I would like to show error and stop the script.
    – Treat
    Oct 7, 2011 at 18:01
  • 2
    Besides the fact that mv is not a perl function, and you are missing a comma in the argument list, there is nothing wrong with this code. It is the code surrounding it -- which you are not showing -- that is responsible.
    – TLP
    Oct 7, 2011 at 18:28
  • 1
    Also, an infinite loop can be stopped with CTRL-C. You do not need to close putty.
    – TLP
    Oct 7, 2011 at 21:17

2 Answers 2

2
 use autodie;
 rename($file, "$dir/$newname")
  • If it fails to rename for any reason it'll die. If the file isn't there it obviously failed to rename and that will be caught as well.
1
  • mv can also autodie. use File::Copy qw(mv); use autodie qw(:all mv); mv $file, "$new_file/$1";
    – daxim
    Oct 8, 2011 at 15:03
0

What about this then:

if ( -f $file ) {
  rename($file, "$dir/$newname")
    or die("Could not rename '$file' to '$dir/$newname'");
} else {
  die("File '$file' does not exist");
}

Please read the manual for the rename() function to see its limitations (perldoc -f rename) and what you might want to do about it (e.g., use move() from the File::Copy module).

4
  • 1
    That introduces a very slight race condition where the file could disappear between the -f $file and the rename() call.
    – CanSpice
    Oct 7, 2011 at 18:34
  • 1
    Include "$!" in the error message and you won't need the if/else. Oct 7, 2011 at 19:04
  • @cansp Can you elaborate on that?
    – TLP
    Oct 7, 2011 at 19:41
  • @CanSpice, in which case it will die when rename() fails rather than in the else. Not a big problem. It would be better, of course, to use $! as @Kieth suggests. Oct 7, 2011 at 20:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .