Renaming File

Hi,
I am currently using the script below to delete a line from a file. The script is running on an NT system and works fine up until the part where the tmp file is renamed to the live file. If there a different way of doing this or how do I make sure that the renaming goes through?

sub delt{
$file = "$keyfile";
open (FILE,"$file");
 open (TMPFL,">>key.tmp");
@keys = <FILE>;
 $q = 0;
  foreach $line (@keys){
     chomp($line);
     if ($key ne $line) {print TMPFL "$line\n";}
  }
  close(TMPFL);
  close(FILE);
  rename "key.tmp", $file || die("Unable to rename.");
}
MAXcomAsked:
Who is Participating?
 
Kim RyanConnect With a Mentor IT ConsultantCommented:
Your code looks OK as you test for the return status of the rename function (1 for success). Are you sure $file contains a valid file name? WHat errors are you getting?

You can use this to achive the same thing.
use File::Copy;
&File::Copy::move("key.tmp",$file;);

unlink($file); is the way to delete a file. But if you rename it, there is no need to delete it.



       
0
 
MAXcomAuthor Commented:
doing "rm $file;" seems to have no effect and doesnt delete the file.
0
 
MAXcomAuthor Commented:
great! unlink did it
0
[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

 
ozoCommented:
Your function may do interesting things if more than one processes try to run it at the same time.
$file seems to be unnecessarily interpolated twice.
For a large file, it may be more memory efficient to process one line at a time than to read the entire file into memory.
the last line in TMPFL will end in \n even if the last line in FILE did not.
You aren't checking the success of your opens
Altering global variables within a sub may be unexpected to the caller
0
 
ozoCommented:
rename "key.tmp", $file || die("Unable to rename.");
parses as
 rename "key.tmp", ($file || die("Unable to rename."));
0
 
MAXcomAuthor Commented:
ozo, how many points do you want to optimize that function since its crucial to what im doing?
0
 
ozoCommented:
I'm not sure what you want to optimize for, if speed, it probably runs about as fast as disk reads/writes now.
Optimizing for code simplicity, I might have written something like

sub delt{
   local $^I=".tmp"; local @ARGV=($file);
   $key .= $/;
   while( <> ){
      print unless $_ eq $key;
   }
   chomp $key;
}

(except that I would have passed parameters instead of globals)
0
All Courses

From novice to tech pro — start learning today.