AlexFromNJ has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I'm trying to write something with "flock" and need to take care of ALL the special cases, for example - when a filehandle got closed before the flock call:
my $result = sysopen my $handle, "abc", O_WRONLY | O_CREAT; close $handle; eval {$result = flock $handle, LOCK_EX | LOCK_NB}; if ($@) { print "------$@------"; }
How to make Perl NOT to throw out the message below? (it's without dashes, so it's not from my "print")
flock() on closed filehandle $handle at ...line ...
(I want just to detect this case, I don't want any confusing messages)

Thanks,
Alex

Replies are listed 'Best First'.
Re: A flock question
by SuicideJunkie (Vicar) on Oct 26, 2011 at 17:44 UTC

    One simple way is to just NOT close your filehandles manually.

    Simply let them fall out of scope when you're done with them, and they will close automagically. That way, you can't try to flock a closed filehandle, because you don't have a reference to it.

Re: A flock question
by duelafn (Parson) on Oct 26, 2011 at 17:43 UTC

    Disable warnings in the eval

    #!/usr/bin/perl -w use strict; use warnings; use 5.010; use Fcntl qw/ O_WRONLY O_CREAT LOCK_EX LOCK_NB /; my $result = sysopen my $handle, "abc", O_WRONLY | O_CREAT; close $handle; eval { no warnings; $result = flock $handle, LOCK_EX | LOCK_NB }; if ($@) { say "------$@------"; } say "Done: ", $result ? "Success" : "Failed";

    Good Day,
        Dean

      no warnings 'closed';
      would be more appropriate.
Re: A flock question
by jwkrahn (Abbot) on Oct 26, 2011 at 22:12 UTC

    Maybe you want something like this:

    if ( defined fileno $handle ) { $result = flock $handle, LOCK_EX | LOCK_NB; }
Re: A flock question
by Marshall (Canon) on Oct 26, 2011 at 23:40 UTC
    Another way is to insert your own WARN or DIE hander...and you just do what you want...
    #!/usr/bin/perl -w use strict; use Fcntl qw(:DEFAULT :flock); my $handle; { local $SIG{__WARN__} = sub { my $msg = shift; print STDERR "*** my message **** $msg"; }; sysopen ($handle, "abc", O_WRONLY | O_CREAT ) or warn "blah"; close $handle; flock ($handle, LOCK_EX | LOCK_NB) or warn "unable to flock"; } __END__ *** my message **** flock() on closed filehandle $handle at C:\TEMP\fl +ockFail.pl line 17. *** my message **** unable to flock at C:\TEMP\flockFail.pl line 17.
    Update: I know that others will disagree, but I think that in this case:
    flock ($handle, LOCK_EX | LOCK_NB), that the extra parens add value and shows that these params go with "flock". Perl allows the parens to omitted in many cases. But I do not think that it is "best practice" to do so in every case where it is allowed. Just because the language allows it does not mean that you should do it. Clarity should be a main point.