hardburn has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to write a subroutine that opens a file, optionally decompressing (using IO::Zlib) and locking. Current code:
sub open_file { my $file = shift || return; my $lock = 0; my $compress = shift; my $fh; if($compress) { use IO::Zlib; $fh = IO::Zlib->new($file, 'rb') or die "Couldn't open file: $!\n"; } else { open($fh, '<', $file) or die "Couldn't open file: $!\n"; } if($lock) { use Fcntl qw(:DEFAULT :flock); flock($fh, LOCK_SH) or die "Couldn't lock file: $!\n"; } return $fh; }
The above will fail if you want to both lock and decompress the file. This is somewhat obvious, since when $fh is inititlized using IO::Zlib, it doesn't really hold a file descriptor.
I've also tried using the tie interface on IO::Zlib instead of calling IO::Zlib->new():
tie $fh, 'IO::Zlib', $file, "rb";
But this fails with a message Can't use string ("IO::Zlib") as a symbol ref while "strict refs" in use at /usr/local/lib/perl5/site_perl/5.8.0/IO/Zlib.pm line 317. Bug in my code or in IO::Zlib?
Doing it via tie or IO::Zlib->new() or some other clever way is fine by me, as long as you can do both locking and transparent decompression.
----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer
Note: All code is untested, unless otherwise stated
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: IO::Zlib and flock
by perlplexer (Hermit) on May 21, 2003 at 17:03 UTC | |
by hardburn (Abbot) on May 21, 2003 at 17:28 UTC | |
|
Re: IO::Zlib and flock
by halley (Prior) on May 21, 2003 at 17:27 UTC | |
by hardburn (Abbot) on May 21, 2003 at 17:32 UTC | |
by perlplexer (Hermit) on May 21, 2003 at 17:44 UTC | |
by halley (Prior) on May 21, 2003 at 17:54 UTC |