用base64解码一个文本文件gzip并读取它

时间:2015-04-15 09:54:57

标签: perl base64 gzip

我从系统中检索一个文本文件,该文件原样(按顺序):

  1. gzipped
  2. 使用base64编码
  3. 所以我想在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;
    

    但它不起作用,$ output变量仍然是undef。

    [编辑]

    我放弃了只通过变量传递。 我通过在每个阶段创建一个新文件来改变我的脚本:

    #!/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);
    

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我会在解码前将整个文件放在一个字符串中:

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

my $uncom = uncompress($dec)

答案 2 :(得分:0)

根据Compress :: Zlib doc,尝试同时打开和阅读:

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;