Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question

migrated from stackoverflow.com Oct 10 '11 at 10:44

This question came from our site for professional and enthusiast programmers.

    
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(). –  Kusalananda Oct 7 '11 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 '11 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 '11 at 18:28
1  
Also, an infinite loop can be stopped with CTRL-C. You do not need to close putty. –  TLP Oct 7 '11 at 21:17

2 Answers 2

up vote 2 down vote accepted
 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.
share|improve this answer
    
mv can also autodie. use File::Copy qw(mv); use autodie qw(:all mv); mv $file, "$new_file/$1"; –  daxim Oct 8 '11 at 15:03

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).

share|improve this answer
1  
That introduces a very slight race condition where the file could disappear between the -f $file and the rename() call. –  CanSpice Oct 7 '11 at 18:34
1  
Include "$!" in the error message and you won't need the if/else. –  Keith Thompson Oct 7 '11 at 19:04
    
@cansp Can you elaborate on that? –  TLP Oct 7 '11 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. –  Kusalananda Oct 7 '11 at 20:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.