2015-04-15 59 views
0

我从系统中检索其已作为(按顺序)的文本文件:解码使用Base64文本文件gzip压缩和阅读

  1. gzip压缩
  2. 用base64编码

所以我想用Perl来解码它,解压并读取它,而不通过中间文件。

我试过如下:

use Compress::Zlib; 
use MIME::Base64; 

my $workingDir = "./log/"; 
my $inputFile = $workingDir . "log_result_base64.txt"; 
my $readtmp =''; 

open (INPFIC, $inputFile) or die "ERROR: Impossible to open file  ($inputFile)\n"; 
while (my $buf = <INPFIC>) { 
    $readtmp .= decode_base64($buf); 
} 
close(INPFIC); 

my $output = uncompress($readtmp); 

print $output; 

但它不工作,$输出变量仍然是联合国民主基金。

[编辑]

我放弃了通过只通过Variable来完成它。

#!/usr/bin/perl 
use strict ; 
use IO::Uncompress::Gunzip qw(gunzip $GunzipError) ; 
use MIME::Base64; 

my $inputFile = $workingDir . "log_inbase64.txt"; 
my $inputFilegz = $workingDir . "log.txt.gz"; 
my $inputFileuncomp = $workingDir . "log.txt"; 

my @out; 
my @readtmp; 
my $readtmp; 

# Reading the file encoded in base64 
open (INPFIC, $inputFile) or die "ERROR: Impossible to open file  ($inputFile)\n"; 
my @readtmp = <INPFIC>; 
close(INPFIC); 
$readtmp = join('',@readtmp); 

# Decode in base64 to retreive a Gzip file 
my $out = decode_base64($readtmp); 
open my $fh, '>', $inputFilegz or die $!; 
binmode $fh; 
print $fh $out; 
close $fh; 

# Decompress the early created gzip file 
gunzip $inputFilegz => $inputFileuncomp 
    or die "gunzip failed: $GunzipError\n"; 

# Reading the Text file 
open (INPFIC, $inputFileuncomp) or die "ERROR: Impossible to open file  ($inputFileuncomp)\n"; 
my @out = <INPFIC>; 
close(INPFIC); 

回答

1

uncompress方法不适用于用gzip压缩的数据。

IO::Uncompress::Gunzip如果要将所有内容都保存在内存中,可以使用标量引用而不是文件名。

示例代码:

use IO::Uncompress::Gunzip qw(gunzip $GunzipError); 
use MIME::Base64 qw(decode_base64); 

my $tmp = decode_base64 do { 
    local $/; 
    <DATA> 
}; 

gunzip \$tmp => \my $data or die "Could not gunzip: $GunzipError"; 
print $data; 

__DATA__ 
H4sIAHWHLlUAAwvJyCxWAKLi/NxUhZLU4hKFlMSSRC4AsSDaaxcAAAA= 

应该产生:

This is some test data 
+0

谢谢,你的解决方案工作正常 – Maximilien

0

我把整个文件中的字符串解码之前: 我在每个阶段创建一个新的文件,改变了我的脚本

local $/ = undef; 
my $str = <INPFIC> 
my $dec = decode_base64 $str; 

my $uncom = uncompress($dec) 
+0

我只是测试和我有同样的结果在我上面的代码。 – Maximilien

0

根据压缩:: Zlib压缩文档,请尝试打开和读取在同一时间:

my $workingDir = "./log/"; 
my $inputFile = $workingDir . "log_result_base64.txt"; 
my $buffer; 
my $output; 
my $gz = gzopen($inputFile,"rb") 
      or die "Cannot open $inputFile: $gzerrno\n" ; 

     while ($gz->gzread($buffer) > 0){ 
       $output .= decode_base64 $buffer; 
     } 

     die "Error reading from $inputFile: $gzerrno" . ($gzerrno+0) . "\n" 
      if $gzerrno != Z_STREAM_END ; 

     $gz->gzclose(); 
print $output; 
+0

在我的情况下,我必须在解压缩之前在base64文件中解码。 – Maximilien

+0

压缩文件不是字符串,也不是编码文本。它可能包含文本文件,但这不是一回事。这只是二进制数据。 –