2 # Author : Paul Marquess
3 # Created : 30 January 2005
6 # Copyright (c) 1995-2005 Paul Marquess. All rights reserved.
7 # This program is free software; you can redistribute it and/or
8 # modify it under the same terms as Perl itself.
11 package Compress::Zlib;
21 our ($VERSION, @ISA, @EXPORT, $AUTOLOAD);
22 our ($deflateDefault, $deflateParamsDefault, $inflateDefault);
27 # Items to export into callers namespace by default. Note: do not export
28 # names by default without a very good reason. Use EXPORT_OK instead.
29 # Do not simply export all your public functions/methods/constants.
86 ($constname = $AUTOLOAD) =~ s/.*:://;
87 my ($error, $val) = constant($constname);
88 Carp::croak $error if $error;
90 *{$AUTOLOAD} = sub { $val };
96 XSLoader::load('Compress::Zlib', $VERSION);
99 local @ISA = qw(DynaLoader);
100 bootstrap Compress::Zlib $VERSION ;
103 # Preloaded methods go here.
109 return ((UNIVERSAL::isa($fh,'GLOB') or UNIVERSAL::isa(\$fh,'GLOB'))
110 and defined fileno($fh) )
118 return (! ref $name and UNIVERSAL::isa(\$name, 'SCALAR')) ;
123 my ($file, $mode) = @_ ;
125 if (isaFilehandle $file) {
126 IO::Handle::flush($file) ;
127 my $offset = tell($file) ;
128 gzdopen_(fileno($file), $mode, $offset) ;
130 elsif (isaFilename $file) {
131 gzopen_($file, $mode)
134 croak "gzopen: file parameter is not a filehandle or filename"
138 sub ParseParameters($@)
140 my ($default, @rest) = @_ ;
141 my (%got) = %$default ;
144 my $sub = (caller(1))[3] ;
147 # allow the options to be passed as a hash reference or
148 # as the complete hash.
151 croak "$sub: parameter is not a reference to a hash"
152 if ref $rest[0] ne "HASH" ;
154 %options = %{ $rest[0] } ;
158 croak "$sub: Expected even number of parameters, got $count"
163 while (($key, $value) = each %options)
167 if (exists $default->{$key})
168 { $got{$key} = $value }
170 { push (@Bad, $key) }
174 my ($bad) = join(", ", @Bad) ;
175 croak "unknown key value(s) @Bad" ;
182 'Level' => Z_DEFAULT_COMPRESSION(),
183 'Method' => Z_DEFLATED(),
184 'WindowBits' => MAX_WBITS(),
185 'MemLevel' => MAX_MEM_LEVEL(),
186 'Strategy' => Z_DEFAULT_STRATEGY(),
191 $deflateParamsDefault = {
198 'WindowBits' => MAX_WBITS(),
206 my ($got) = ParseParameters($deflateDefault, @_) ;
208 croak "deflateInit: Bufsize must be >= 1, you specified $got->{Bufsize}"
209 unless $got->{Bufsize} >= 1;
210 _deflateInit($got->{Level}, $got->{Method}, $got->{WindowBits},
211 $got->{MemLevel}, $got->{Strategy}, $got->{Bufsize},
212 $got->{Dictionary}) ;
218 my ($got) = ParseParameters($inflateDefault, @_) ;
220 croak "inflateInit: Bufsize must be >= 1, you specified $got->{Bufsize}"
221 unless $got->{Bufsize} >= 1;
222 _inflateInit($got->{WindowBits}, $got->{Bufsize}, $got->{Dictionary});
226 sub Compress::Zlib::deflateStream::deflateParams
229 my ($got) = ParseParameters($deflateParamsDefault, @_) ;
230 croak "deflateParams needs Level and/or Strategy"
231 unless defined $got->{Level} || defined $got->{Strategy};
233 croak "deflateParams: Bufsize must be >= 1, you specified $got->{Bufsize}"
234 unless !defined $got->{Bufsize} || $got->{Bufsize} >= 1;
237 if (defined $got->{Level})
240 { $got->{Level} = 0 }
242 if (defined $got->{Strategy})
245 { $got->{Strategy} = 0 }
248 if !defined $got->{Bufsize};
250 $self->_deflateParams($flags, $got->{Level}, $got->{Strategy},
257 my ($x, $output, $out, $err, $in) ;
261 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
267 my $level = (@_ == 2 ? $_[1] : Z_DEFAULT_COMPRESSION() );
270 if ( (($x, $err) = deflateInit(Level => $level))[1] == Z_OK()) {
272 ($output, $err) = $x->deflate($in) ;
273 return undef unless $err == Z_OK() ;
275 ($out, $err) = $x->flush() ;
276 return undef unless $err == Z_OK() ;
278 return ($output . $out) ;
288 my ($x, $output, $err, $in) ;
292 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
298 if ( (($x, $err) = inflateInit())[1] == Z_OK()) {
300 ($output, $err) = $x->__unc_inflate($in) ;
301 return undef unless $err == Z_STREAM_END() ;
311 use constant MAGIC1 => 0x1f ;
312 use constant MAGIC2 => 0x8b ;
313 use constant OSCODE => 3 ;
315 use constant FTEXT => 1 ;
316 use constant FHCRC => 2 ;
317 use constant FEXTRA => 4 ;
318 use constant FNAME => 8 ;
319 use constant FCOMMENT => 16 ;
320 use constant NULL => pack("C", 0) ;
321 use constant RESERVED => 0xE0 ;
323 use constant MIN_HDR_SIZE => 10 ; # minimum gzip header size
328 -Level => Z_BEST_COMPRESSION(),
329 -WindowBits => - MAX_WBITS(),
333 # write a minimal gzip header
335 push @m, pack("C" . MIN_HDR_SIZE,
336 MAGIC1, MAGIC2, Z_DEFLATED(), 0,0,0,0,0,0, OSCODE) ;
338 # if the deflation buffer isn't a reference, make it one
339 my $string = (ref $_[0] ? $_[0] : \$_[0]) ;
341 my ($output, $status) = $x->deflate($string) ;
346 ($output, $status) = $x->flush() ;
351 push @m, pack("V V", crc32($string), $x->total_in());
356 sub _removeGzipHeader($)
360 return Z_DATA_ERROR()
361 if length($$string) < MIN_HDR_SIZE ;
363 my ($magic1, $magic2, $method, $flags, $time, $xflags, $oscode) =
364 unpack ('CCCCVCC', $$string);
366 return Z_DATA_ERROR()
367 unless $magic1 == MAGIC1 and $magic2 == MAGIC2 and
368 $method == Z_DEFLATED() and !($flags & RESERVED()) ;
369 substr($$string, 0, MIN_HDR_SIZE) = '' ;
374 return Z_DATA_ERROR()
375 if length($$string) < 2 ;
377 my ($extra_len) = unpack ('v', $$string);
379 return Z_DATA_ERROR()
380 if length($$string) < $extra_len ;
382 substr($$string, 0, $extra_len) = '';
388 my $name_end = index ($$string, NULL);
389 return Z_DATA_ERROR()
391 substr($$string, 0, $name_end + 1) = '';
395 if ($flags & FCOMMENT)
397 my $comment_end = index ($$string, NULL);
398 return Z_DATA_ERROR()
399 if $comment_end == -1 ;
400 substr($$string, 0, $comment_end + 1) = '';
406 return Z_DATA_ERROR()
407 if length ($$string) < 2 ;
408 substr($$string, 0, 2) = '';
417 # if the buffer isn't a reference, make it one
418 my $string = (ref $_[0] ? $_[0] : \$_[0]);
420 _removeGzipHeader($string) == Z_OK()
423 my $bufsize = length $$string > 4096 ? length $$string : 4096 ;
424 my $x = inflateInit( -WindowBits => - MAX_WBITS(),
425 -Bufsize => $bufsize)
427 my ($output, $status) = $x->inflate($string);
429 unless $status == Z_STREAM_END();
431 if (length $$string >= 8)
433 my ($crc, $len) = unpack ("VV", substr($$string, 0, 8));
434 substr($$string, 0, 8) = '';
436 unless $len == length($output) and
437 $crc == crc32($output);
447 # Autoload methods go after __END__, and are processed by the autosplit program.
456 Compress::Zlib - Interface to zlib compression library
462 ($d, $status) = deflateInit( [OPT] ) ;
463 ($out, $status) = $d->deflate($buffer) ;
464 $status = $d->deflateParams([OPT]) ;
465 ($out, $status) = $d->flush() ;
471 ($i, $status) = inflateInit( [OPT] ) ;
472 ($out, $status) = $i->inflate($buffer) ;
473 $status = $i->inflateSync($buffer) ;
479 $dest = compress($source, [$level]) ;
480 $dest = uncompress($source) ;
482 $gz = gzopen($filename or filehandle, $mode) ;
483 $bytesread = $gz->gzread($buffer [,$size]) ;
484 $bytesread = $gz->gzreadline($line) ;
485 $byteswritten = $gz->gzwrite($buffer) ;
486 $status = $gz->gzflush($flush) ;
487 $status = $gz->gzclose() ;
488 $status = $gz->gzeof() ;
489 $status = $gz->gzsetparams($level, $strategy) ;
490 $errstring = $gz->gzerror() ;
493 $dest = Compress::Zlib::memGzip($buffer) ;
494 $dest = Compress::Zlib::memGunzip($buffer) ;
496 $crc = adler32($buffer [,$crc]) ;
497 $crc = crc32($buffer [,$crc]) ;
503 The I<Compress::Zlib> module provides a Perl interface to the I<zlib>
504 compression library (see L</AUTHOR> for details about where to get
505 I<zlib>). Most of the functionality provided by I<zlib> is available
506 in I<Compress::Zlib>.
508 The module can be split into two general areas of functionality, namely
509 in-memory compression/decompression and read/write access to I<gzip>
510 files. Each of these areas will be discussed separately below.
514 The interface I<Compress::Zlib> provides to the in-memory I<deflate>
515 (and I<inflate>) functions has been modified to fit into a Perl model.
517 The main difference is that for both inflation and deflation, the Perl
518 interface will I<always> consume the complete input buffer before
519 returning. Also the output buffer returned will be automatically grown
520 to fit the amount of output available.
522 Here is a definition of the interface available:
525 =head2 B<($d, $status) = deflateInit( [OPT] )>
527 Initialises a deflation stream.
529 It combines the features of the I<zlib> functions B<deflateInit>,
530 B<deflateInit2> and B<deflateSetDictionary>.
532 If successful, it will return the initialised deflation stream, B<$d>
533 and B<$status> of C<Z_OK> in a list context. In scalar context it
534 returns the deflation stream, B<$d>, only.
536 If not successful, the returned deflation stream (B<$d>) will be
537 I<undef> and B<$status> will hold the exact I<zlib> error code.
539 The function optionally takes a number of named options specified as
540 C<-Name=E<gt>value> pairs. This allows individual options to be
541 tailored without having to specify them all in the parameter list.
543 For backward compatibility, it is also possible to pass the parameters
544 as a reference to a hash containing the name=>value pairs.
546 The function takes one optional parameter, a reference to a hash. The
547 contents of the hash allow the deflation interface to be tailored.
549 Here is a list of the valid options:
555 Defines the compression level. Valid values are 0 through 9,
556 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
557 C<Z_DEFAULT_COMPRESSION>.
559 The default is C<-Level =E<gt>Z_DEFAULT_COMPRESSION>.
563 Defines the compression method. The only valid value at present (and
564 the default) is C<-Method =E<gt>Z_DEFLATED>.
568 For a definition of the meaning and valid values for B<WindowBits>
569 refer to the I<zlib> documentation for I<deflateInit2>.
571 Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
575 For a definition of the meaning and valid values for B<MemLevel>
576 refer to the I<zlib> documentation for I<deflateInit2>.
578 Defaults to C<-MemLevel =E<gt>MAX_MEM_LEVEL>.
582 Defines the strategy used to tune the compression. The valid values are
583 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
585 The default is C<-Strategy =E<gt>Z_DEFAULT_STRATEGY>.
589 When a dictionary is specified I<Compress::Zlib> will automatically
590 call B<deflateSetDictionary> directly after calling B<deflateInit>. The
591 Adler32 value for the dictionary can be obtained by calling the method
594 The default is no dictionary.
598 Sets the initial size for the deflation buffer. If the buffer has to be
599 reallocated to increase the size, it will grow in increments of
606 Here is an example of using the B<deflateInit> optional parameter list
607 to override the default buffer size and compression level. All other
608 options will take their default values.
610 deflateInit( -Bufsize => 300,
611 -Level => Z_BEST_SPEED ) ;
614 =head2 B<($out, $status) = $d-E<gt>deflate($buffer)>
617 Deflates the contents of B<$buffer>. The buffer can either be a scalar
618 or a scalar reference. When finished, B<$buffer> will be
619 completely processed (assuming there were no errors). If the deflation
620 was successful it returns the deflated output, B<$out>, and a status
621 value, B<$status>, of C<Z_OK>.
623 On error, B<$out> will be I<undef> and B<$status> will contain the
626 In a scalar context B<deflate> will return B<$out> only.
628 As with the I<deflate> function in I<zlib>, it is not necessarily the
629 case that any output will be produced by this method. So don't rely on
630 the fact that B<$out> is empty for an error test.
633 =head2 B<($out, $status) = $d-E<gt>flush([flush_type])>
635 Typically used to finish the deflation. Any pending output will be
636 returned via B<$out>.
637 B<$status> will have a value C<Z_OK> if successful.
639 In a scalar context B<flush> will return B<$out> only.
641 Note that flushing can seriously degrade the compression ratio, so it
642 should only be used to terminate a decompression (using C<Z_FINISH>) or
643 when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
645 By default the C<flush_type> used is C<Z_FINISH>. Other valid values
646 for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
647 and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
648 C<flush_type> parameter if you fully understand the implications of
649 what it does. See the C<zlib> documentation for details.
651 =head2 B<$status = $d-E<gt>deflateParams([OPT])>
653 Change settings for the deflate stream C<$d>.
655 The list of the valid options is shown below. Options not specified
656 will remain unchanged.
662 Defines the compression level. Valid values are 0 through 9,
663 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
664 C<Z_DEFAULT_COMPRESSION>.
668 Defines the strategy used to tune the compression. The valid values are
669 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
673 =head2 B<$d-E<gt>dict_adler()>
675 Returns the adler32 value for the dictionary.
677 =head2 B<$d-E<gt>msg()>
679 Returns the last error message generated by zlib.
681 =head2 B<$d-E<gt>total_in()>
683 Returns the total number of bytes uncompressed bytes input to deflate.
685 =head2 B<$d-E<gt>total_out()>
687 Returns the total number of compressed bytes output from deflate.
692 Here is a trivial example of using B<deflate>. It simply reads standard
693 input, deflates it and writes it to standard output.
702 my $x = deflateInit()
703 or die "Cannot create a deflation stream\n" ;
705 my ($output, $status) ;
708 ($output, $status) = $x->deflate($_) ;
711 or die "deflation failed\n" ;
716 ($output, $status) = $x->flush() ;
719 or die "deflation failed\n" ;
725 Here is a definition of the interface:
728 =head2 B<($i, $status) = inflateInit()>
730 Initialises an inflation stream.
732 In a list context it returns the inflation stream, B<$i>, and the
733 I<zlib> status code (B<$status>). In a scalar context it returns the
734 inflation stream only.
736 If successful, B<$i> will hold the inflation stream and B<$status> will
739 If not successful, B<$i> will be I<undef> and B<$status> will hold the
742 The function optionally takes a number of named options specified as
743 C<-Name=E<gt>value> pairs. This allows individual options to be
744 tailored without having to specify them all in the parameter list.
746 For backward compatibility, it is also possible to pass the parameters
747 as a reference to a hash containing the name=>value pairs.
749 The function takes one optional parameter, a reference to a hash. The
750 contents of the hash allow the deflation interface to be tailored.
752 Here is a list of the valid options:
758 For a definition of the meaning and valid values for B<WindowBits>
759 refer to the I<zlib> documentation for I<inflateInit2>.
761 Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
765 Sets the initial size for the inflation buffer. If the buffer has to be
766 reallocated to increase the size, it will grow in increments of
773 The default is no dictionary.
777 Here is an example of using the B<inflateInit> optional parameter to
778 override the default buffer size.
780 inflateInit( -Bufsize => 300 ) ;
782 =head2 B<($out, $status) = $i-E<gt>inflate($buffer)>
784 Inflates the complete contents of B<$buffer>. The buffer can either be
785 a scalar or a scalar reference.
787 Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
788 compressed data has been successfully reached.
789 If not successful, B<$out> will be I<undef> and B<$status> will hold
790 the I<zlib> error code.
792 The C<$buffer> parameter is modified by C<inflate>. On completion it
793 will contain what remains of the input buffer after inflation. This
794 means that C<$buffer> will be an empty string when the return status is
795 C<Z_OK>. When the return status is C<Z_STREAM_END> the C<$buffer>
796 parameter will contains what (if anything) was stored in the input
797 buffer after the deflated data stream.
799 This feature is useful when processing a file format that encapsulates
800 a compressed data stream (e.g. gzip, zip).
802 =head2 B<$status = $i-E<gt>inflateSync($buffer)>
804 Scans C<$buffer> until it reaches either a I<full flush point> or the
807 If a I<full flush point> is found, C<Z_OK> is returned and C<$buffer>
808 will be have all data up to the flush point removed. This can then be
809 passed to the C<deflate> method.
811 Any other return code means that a flush point was not found. If more
812 data is available, C<inflateSync> can be called repeatedly with more
813 compressed data until the flush point is found.
816 =head2 B<$i-E<gt>dict_adler()>
818 Returns the adler32 value for the dictionary.
820 =head2 B<$i-E<gt>msg()>
822 Returns the last error message generated by zlib.
824 =head2 B<$i-E<gt>total_in()>
826 Returns the total number of bytes compressed bytes input to inflate.
828 =head2 B<$i-E<gt>total_out()>
830 Returns the total number of uncompressed bytes output from inflate.
834 Here is an example of using B<inflate>.
841 my $x = inflateInit()
842 or die "Cannot create a inflation stream\n" ;
848 my ($output, $status) ;
849 while (read(STDIN, $input, 4096))
851 ($output, $status) = $x->inflate(\$input) ;
854 if $status == Z_OK or $status == Z_STREAM_END ;
856 last if $status != Z_OK ;
859 die "inflation failed\n"
860 unless $status == Z_STREAM_END ;
862 =head1 COMPRESS/UNCOMPRESS
864 Two high-level functions are provided by I<zlib> to perform in-memory
865 compression/uncompression of RFC1950 data streams. They are called
866 B<compress> and B<uncompress>.
868 The two Perl subs defined below provide the equivalent
873 =item B<$dest = compress($source [, $level] ) ;>
875 Compresses B<$source>. If successful it returns the
876 compressed data. Otherwise it returns I<undef>.
878 The source buffer can either be a scalar or a scalar reference.
880 The B<$level> paramter defines the compression level. Valid values are
881 0 through 9, C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>,
882 C<Z_BEST_COMPRESSION>, and C<Z_DEFAULT_COMPRESSION>.
883 If B<$level> is not specified C<Z_DEFAULT_COMPRESSION> will be used.
886 =item B<$dest = uncompress($source) ;>
888 Uncompresses B<$source>. If successful it returns the uncompressed
889 data. Otherwise it returns I<undef>.
891 The source buffer can either be a scalar or a scalar reference.
895 Please note: the two functions defined above are I<not> compatible with
896 the Unix commands of the same name.
898 =head1 GZIP INTERFACE
900 A number of functions are supplied in I<zlib> for reading and writing
901 I<gzip> files. This module provides an interface to most of them. In
902 general the interface provided by this module operates identically to
903 the functions provided by I<zlib>. Any differences are explained
908 =item B<$gz = gzopen(filename or filehandle, mode)>
910 This function operates identically to the I<zlib> equivalent except
911 that it returns an object which is used to access the other I<gzip>
914 As with the I<zlib> equivalent, the B<mode> parameter is used to
915 specify both whether the file is opened for reading or writing and to
916 optionally specify a a compression level. Refer to the I<zlib>
917 documentation for the exact format of the B<mode> parameter.
919 If a reference to an open filehandle is passed in place of the
920 filename, gzdopen will be called behind the scenes. The third example
921 at the end of this section, I<gzstream>, uses this feature.
923 =item B<$bytesread = $gz-E<gt>gzread($buffer [, $size]) ;>
925 Reads B<$size> bytes from the compressed file into B<$buffer>. If
926 B<$size> is not specified, it will default to 4096. If the scalar
927 B<$buffer> is not large enough, it will be extended automatically.
929 Returns the number of bytes actually read. On EOF it returns 0 and in
930 the case of an error, -1.
932 =item B<$bytesread = $gz-E<gt>gzreadline($line) ;>
934 Reads the next line from the compressed file into B<$line>.
936 Returns the number of bytes actually read. On EOF it returns 0 and in
937 the case of an error, -1.
939 It is legal to intermix calls to B<gzread> and B<gzreadline>.
941 At this time B<gzreadline> ignores the variable C<$/>
942 (C<$INPUT_RECORD_SEPARATOR> or C<$RS> when C<English> is in use). The
943 end of a line is denoted by the C character C<'\n'>.
945 =item B<$byteswritten = $gz-E<gt>gzwrite($buffer) ;>
947 Writes the contents of B<$buffer> to the compressed file. Returns the
948 number of bytes actually written, or 0 on error.
950 =item B<$status = $gz-E<gt>gzflush($flush) ;>
952 Flushes all pending output to the compressed file.
953 Works identically to the I<zlib> function it interfaces to. Note that
954 the use of B<gzflush> can degrade compression.
956 Returns C<Z_OK> if B<$flush> is C<Z_FINISH> and all output could be
957 flushed. Otherwise the zlib error code is returned.
959 Refer to the I<zlib> documentation for the valid values of B<$flush>.
961 =item B<$status = $gz-E<gt>gzeof() ;>
963 Returns 1 if the end of file has been detected while reading the input
964 file, otherwise returns 0.
966 =item B<$gz-E<gt>gzclose>
968 Closes the compressed file. Any pending data is flushed to the file
971 =item B<$gz-E<gt>gzsetparams($level, $strategy>
973 Change settings for the deflate stream C<$gz>.
975 The list of the valid options is shown below. Options not specified
976 will remain unchanged.
978 Note: This method is only available if you are running zlib 1.0.6 or better.
984 Defines the compression level. Valid values are 0 through 9,
985 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
986 C<Z_DEFAULT_COMPRESSION>.
990 Defines the strategy used to tune the compression. The valid values are
991 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
995 =item B<$gz-E<gt>gzerror>
997 Returns the I<zlib> error message or number for the last operation
998 associated with B<$gz>. The return value will be the I<zlib> error
999 number when used in a numeric context and the I<zlib> error message
1000 when used in a string context. The I<zlib> error number constants,
1001 shown below, are available for use.
1013 The B<$gzerrno> scalar holds the error code associated with the most
1014 recent I<gzip> routine. Note that unlike B<gzerror()>, the error is
1015 I<not> associated with a particular file.
1017 As with B<gzerror()> it returns an error number in numeric context and
1018 an error message in string context. Unlike B<gzerror()> though, the
1019 error message will correspond to the I<zlib> message when the error is
1020 associated with I<zlib> itself, or the UNIX error message when it is
1021 not (i.e. I<zlib> returned C<Z_ERRORNO>).
1023 As there is an overlap between the error numbers used by I<zlib> and
1024 UNIX, B<$gzerrno> should only be used to check for the presence of
1025 I<an> error in numeric context. Use B<gzerror()> to check for specific
1026 I<zlib> errors. The I<gzcat> example below shows how the variable can
1034 Here is an example script which uses the interface. It implements a
1040 use Compress::Zlib ;
1042 die "Usage: gzcat file...\n"
1047 foreach $file (@ARGV) {
1050 my $gz = gzopen($file, "rb")
1051 or die "Cannot open $file: $gzerrno\n" ;
1053 print $buffer while $gz->gzread($buffer) > 0 ;
1055 die "Error reading from $file: $gzerrno" . ($gzerrno+0) . "\n"
1056 if $gzerrno != Z_STREAM_END ;
1061 Below is a script which makes use of B<gzreadline>. It implements a
1062 very simple I<grep> like script.
1067 use Compress::Zlib ;
1069 die "Usage: gzgrep pattern file...\n"
1072 my $pattern = shift ;
1076 foreach $file (@ARGV) {
1077 my $gz = gzopen($file, "rb")
1078 or die "Cannot open $file: $gzerrno\n" ;
1080 while ($gz->gzreadline($_) > 0) {
1081 print if /$pattern/ ;
1084 die "Error reading from $file: $gzerrno\n"
1085 if $gzerrno != Z_STREAM_END ;
1090 This script, I<gzstream>, does the opposite of the I<gzcat> script
1091 above. It reads from standard input and writes a gzip file to standard
1097 use Compress::Zlib ;
1099 binmode STDOUT; # gzopen only sets it on the fd
1101 my $gz = gzopen(\*STDOUT, "wb")
1102 or die "Cannot open stdout: $gzerrno\n" ;
1106 or die "error writing: $gzerrno\n" ;
1111 =head2 Compress::Zlib::memGzip
1113 This function is used to create an in-memory gzip file.
1114 It creates a minimal gzip header.
1116 $dest = Compress::Zlib::memGzip($buffer) ;
1118 If successful, it returns the in-memory gzip file, otherwise it returns
1121 The buffer parameter can either be a scalar or a scalar reference.
1123 =head2 Compress::Zlib::memGunzip
1125 This function is used to uncompress an in-memory gzip file.
1127 $dest = Compress::Zlib::memGunzip($buffer) ;
1129 If successful, it returns the uncompressed gzip file, otherwise it
1132 The buffer parameter can either be a scalar or a scalar reference. The
1133 contents of the buffer parameter are destroyed after calling this
1136 =head1 CHECKSUM FUNCTIONS
1138 Two functions are provided by I<zlib> to calculate a checksum. For the
1139 Perl interface, the order of the two parameters in both functions has
1140 been reversed. This allows both running checksums and one off
1141 calculations to be done.
1143 $crc = adler32($buffer [,$crc]) ;
1144 $crc = crc32($buffer [,$crc]) ;
1146 The buffer parameters can either be a scalar or a scalar reference.
1148 If the $crc parameters is C<undef>, the crc value will be reset.
1150 =head1 ACCESSING ZIP FILES
1152 Although it is possible to use this module to access .zip files, there
1153 is a module on CPAN that will do all the hard work for you. Check out
1155 http://www.cpan.org/modules/by-module/Archive/Archive-Zip-*.tar.gz
1157 Assuming you don't want to use this module to access zip files there
1158 are a number of undocumented features in the zlib library you need to
1165 When calling B<inflateInit> or B<deflateInit> the B<WindowBits> parameter
1166 must be set to C<-MAX_WBITS>. This disables the creation of the zlib
1171 The zlib function B<inflate>, and so the B<inflate> method supplied in
1172 this module, assume that there is at least one trailing byte after the
1173 compressed data stream. Normally this isn't a problem because both
1174 the gzip and zip file formats will guarantee that there is data directly
1175 after the compressed data stream.
1181 All the I<zlib> constants are automatically imported when you make use
1182 of I<Compress::Zlib>.
1186 The I<Compress::Zlib> module was written by Paul Marquess,
1187 F<pmqs@cpan.org>. The latest copy of the module can be
1188 found on CPAN in F<modules/by-module/Compress/Compress-Zlib-x.x.tar.gz>.
1190 The primary site for the I<zlib> compression library is
1191 F<http://www.zlib.org>.
1193 =head1 MODIFICATION HISTORY
1195 See the Changes file.