CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Intermediate: Re: [gregarios] Database Unexpected Erasure Problem: Edit Log


May 23, 2002, 12:42 PM

Views: 8602
Re: [gregarios] Database Unexpected Erasure Problem

To make more robust programs, that don't have these problems, you can use the following tips and tricks:

- be strict:

use strict;

This disallows to make magical (self appearing) variables. You need to declare a variable with my() first, and all decrations only last until the end of a { } block.

- Declare all variables in the block you use them with my()

my $x = 'value'

- Use the -w switch. (disallows the use of undefined values...), for example:

#!/usr/bin/perl -w 

my $something = function_returning_undef();
print "Something is $something\n";

Usually, undef is an indication of failure, or your logic failed. You can always check for undef with the defined() function.

print "Something is $something\n" if defined $something;   
print "Something is " . ($something || "false") . "\n";

- Use locking using Fcntl constants

use Fcntl qw(:flock);   
flock FILEHANDLE, LOCK_SH; # Other processes can only read (but pause when they want to edit)
flock FILEHANDLE, LOCK_EX; # Every process pauses until you're done editing the file.

- Seek to the EOF when you're appending data... If you're waiting until someones lock is freed, the first might have grown in size.
Put this after your flock(..LOCK_EX) line:

seek(FILEHANDLE, 0, 2) or die "Can't seek EOF: $!";

- Always check for the return type of open.
Either use a if, or throw the error with a open(..) or die "Error: $!"; contruction.

- When you want to update, don't read the file first, and re-open it to write data. Open it with RD_WR access. You can use an extra file as buffer space if you don't want to slurp everything into the memory.

use Fcntl qw(:DEFAULT :flock);   
sysopen(FH, $file, O_CREAT|O_RDWR) or die "Can't rdwr: $!";
flock(FH, LOCK_EX);
my @all_data = <FH>; # Slurp into memory.
# edit @all_data...

seek(FH, 0, 0) or die "Can't seek begin: $!";
truncate(FH, 0) or die "Can't erase contents: $!";
print FH @all_data;

- Use chomp to remove the \n, and not chop.

anything more?

Yet Another Perl Programmer

~~> [url=] <~~
More then 3500 X-Forum [url=]Downloads! Cool

(This post was edited by yapp on May 23, 2002, 1:01 PM)

Edit Log:
Post edited by yapp (User) on May 23, 2002, 12:52 PM
Post edited by yapp (User) on May 23, 2002, 1:01 PM

Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives