Thread: Perl code
View Single Post
Old 08-23-2002, 07:21 PM  
Nbritte
Confirmed User
 
Join Date: Sep 2001
Location: Kentucky USA
Posts: 689
ok here is the long version
&lock2("filename.lock");# lock the file so no one can write while processing data
@data = &readfile("filename");#read the data from the file
unshift(@data,$newline);# shift the array down and add new line to top
&writefile("filename",@data);#write the data back to the file;
if (-e "filename.lock") {unlink("filename.lock")}#remove the lock file so other processes can use it
sub readfile {
$fname = $_[0];
open(INF,"<$fname") || &error("unable to open $fname : $!");
@data = <INF>;
close(INF);
return @data;
}
sub writefile {
($fname,@data) = @_;
open(OUTF,">$fname") || &error("unable to open $fname : $!");
foreach $data (@data) {
chomp($data);
print OUTF"$data\n"; }
close(OUTF);
}
sub lock2 {
$lockf = @_[0];
local($flag) = 0;
foreach (1 .. 5) {
if (-e $lockf) { sleep(1); }
else {
open(LOCK,">$lockf");
close(LOCK);
$flag = 1;
last;
}
}
if ($flag == 0) { &error("Lock file busy"); }
}


Brian
Nbritte is offline   Share thread on Digg Share thread on Twitter Share thread on Reddit Share thread on Facebook Reply With Quote