# from Russell Johnson
# on Tuesday 18 October 2011 20:43:
>> 2. If you are going to write a file with one program and read the
>> file with another program, get in the habit of creating the file
>> atomically. ...
>>
>> use File::Basename;
>> sub writetemp {
>> my $fname = "/tmp/". basename($0) . ".count";
>> open (NEWFILE, ">${fname}.tmp") or die $!;
>> print NEWFILE "$product{name}.value $product{value} $date";
>> close (NEWFILE);
>> rename($fname . ".tmp", $fname) or die $!;
>> }
>
>Excellent suggestion. I will implement this and the other suggestions.
> I'm a novice when it comes to perl. I can usually cobble something
> together, but I learn by example all the time.
And there's always more to learn!
If you're running a program as root and writing a predictably-named file
in a globally writable directory, be aware that knowledge of this
predictable name could be exploited to cause root to overwrite any file
via a symlink. Using a tempfile with a randomized name prevents this.
If you run out of space in /tmp/, close() will return false.
use File::Fu;
sub writetemp {
my $fname = File::Fu->tmp +
(File::Fu->program_name->basename . '.count');
my $fh = File::Fu->temp_file;
print $fh "$product{name}.value $product{value} $date";
close($fh) or die "error closing temp file $!";
$fh->name->rename($fname);
}
You can do that with File::Temp and File::Basename instead (which is all
that happens under the hood) but I use File::Fu so much I forget how to
do it longhand. Also, File::Fu checks the return values and throws an
error for me -- but you could 'use autodie' and even close() would be
checked automatically.
For bedtime reading, try `perldoc -f open`.
--Eric
--
Introducing change is like pulling off a bandage: the pain is a memory
almost as soon as you feel it.
--Paul Graham
---------------------------------------------------
http://scratchcomputing.com
---------------------------------------------------
_______________________________________________
PLUG mailing list
[email protected]
http://lists.pdxlinux.org/mailman/listinfo/plug