in reply to Flock, die and statement order

If an operation dies, all the open handles are closed as part of the normal shutdown. Also, with modern perl, you can use a lexical scalar (my $foo;) and the $foo handle will be closed automatically when it goes out of scope.

It is good policy to check all interaction with the os for errors and die, retry, or otherwise handle the error.

Your nest of conditionals is unnecessarily complicated, therefore. I'd rewrite it something like this:

{ sysopen my $trigger, $config->{xmlpath}.'trigfile.tf', O_WRONLY | O_EXCL | O_CREAT or die $!; flock $trigger, LOCK_EX | LOCK_NB or die $!; print $trigger $/ or die $!; close $trigger or die $!; }
At any stage that dies, the file is closed. if you want to continue in spite of errors, you can replace the die clause with warn $! and last; which will have the same effect on the handle, give the same error message, but will continue at the end of the block. I didn't try to duplicate your html output for errors, but it can be inserted in the error message and CGI::Carp can send the errors to the browser.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Flock, die and statement order
by Ionizor (Pilgrim) on Nov 18, 2002 at 15:30 UTC

    Unfortunately I can't call any function that will output directly, otherwise I would be using warn or die. If I call warn, I'll end up with something that looks like:

    <p>Error Message</p> <html> <head> <title>Error</title> </head> <body> ... </body> </html>

    As it stands right now, the script pushes a message onto the error stack, which is checked later in the script. The user is then informed of any errors or sent to the next form if there were no errors. It's not clear from the above snippet that errors are handled but rest assured that they are.

      Why is warn() going to the page? It should be going to STDERR and the server's error log. If you are handling errors, you can catch the die with an eval block.
      eval { might_die() }; if ($@) { # handle exception }

        I guess I misunderstood where warn() outputs to; my apologies. In any case the error message shouldn't be going to the server's error log because it's a message intended for the script's end user.

        I guess I'm just not clear why an eval block / die is better than the nested ifs I have. The script code is well commented and traps errors so what is the advantage of using die?