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

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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



yapp
User

May 23, 2002, 12:42 PM


Views: 3736
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:

Code
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()

Code
my $x = 'value'


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

Code
#!/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.

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



- Use locking using Fcntl constants


Code
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:

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


Code
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;
clsoe(FH);


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

anything more?

Yet Another Perl Programmer

_________________________________
~~> [url=http://www.codingdomain.com]www.codingdomain.com <~~
More then 3500 X-Forum [url=http://www.codingdomain.com/cgi-perl/downloads/x-forum]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