天天看點

Perl 讀寫 .gz .tgz 等壓縮檔案

原文來自:http://qyiyunso.blog.163.com/blog/static/350776862010111511336701/

1. 使用PERL直接讀取壓縮檔案 use pipe

.gz格式檔案

1
      
open(FIN,"gzip -dc $infilename|") or die ("can not open $infilename\n");      

.tgz(.tar.gz)格式檔案

1
      
open(FIN,"tar -xf $infilename -o|") or die ("can not open $infilename\n");      

7zip格式檔案

1
      
open(FIN,"7za e -so $infilename|") or die ("can not open $infilename\n");      

這個可以直接用

2. 用PerlIO包

1)在*.pl前加上

1
2
      
use lib "/libPath";
use PerlIO::gzip;      

2)在用的時候:

1
2
      
open FI, "<:gzip", "$fi";
open FO, ">:gzip", "$fo";      

3. 用 File::Package;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
      
#!/usr/bin/perl -w
use strict;
 
use File::Package;
 
my $uut='Tie::Gzip';
my $fp='File::Package';
$fp->load_package($uut);
 
tie *GZIP,'Tie::Gzip';
my $gzip=\*GZIP;
open($gzip,"> test.gz");
 
while(my $line=<$gzip>){
chomp $line;
print"$line\n";
}
close $gzip;
 
tie *OUT,'Tie::Gzip';
my $out=\*OUT;
open($out,"> test.gz");
print $out "I want to know more!\n"
close $out;