使用 base64 解码 gzip 压缩的文本文件并读取它

Decode with base64 a text file gzipped and read it

我从系统中检索了一个文本文件(按顺序):

  1. gzipped
  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;

但是不行,$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);

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

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

my $uncom = uncompress($dec)

根据 Compress::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;

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