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

It appears that the FileHandle module does not have a flock method. Does anyone know of a way to flock using FileHandle.pm?

Replies are listed 'Best First'.
Re (tilly) 1: flock with FileHandle.pm?
by tilly (Archbishop) on Aug 24, 2001 at 08:56 UTC
    The object is also a valid filehandle. So you just call:
    flock($fh, $mode) or die "Cannot flock file in $mode: $!";
    If this bothers you, you can just add the following:
    package FileHandle; use Carp; sub lock { my $self = shift; flock($self, 8) or confess("Cannot lock file: $!"); }
    and now you can just call:
    $fh->lock();
    Note that I did not create an unlock method. That is intentional. Files should never be unlocked. Instead you close or drop the filehandle, and they will be unlocked for you by the OS.
      Cool, thanks. This helped a lot. Just out of curiosity, why not unlock the filehandle? I am used to doing:
      flock($fh,2); ...process stuff here... $flock($fh,8);
Re: flock with FileHandle.pm?
by rob_au (Abbot) on Aug 24, 2001 at 09:02 UTC
    From my experience, flock() methods are exported from the Fcntl module which calls on OS-specific methods. For example:
     
    #!/usr/bin/perl use FileHandle; use Fcntl ':flock'; # Create file handle and open file for writing # my $fh = new FileHandle; if ($fh->open(">file")) { # Obtain an exclusive lock on the file handle # flock ($fh, LOCK_EX); # Write to file handle # print $fh "Just another Perl hacker\n"; # Remove exclusive lock on file handle and close file handle # flock ($fh, LOCK_UN); $fh->close; } exit 0;

     
    Update : It turns out that the Fcntl usage only imports the LOCK_EX and LOCK_UN constants, not provides the flock() method - Thanks tilly :)
     

     
    Ooohhh, Rob no beer function well without!