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


In reply to IO::Zlib and flock by hardburn

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.