繁体   English   中英

Perl 等效于 python 编码和 gzip

[英]Perl equivalent for python encode and gzip

我试图在 Perl 中生成一个压缩字符串,它等效于在 Python 中生成的字符串。

Python(产生正确的输出):

import gzip
test_file = 'example.json'

with open(test_file) as f:
    output_data = gzip.compress(f.read().encode())
    print(output_data)

或多或少我一直在尝试在 Perl 中工作:

use Encode;
use IO::Compress::Gzip qw/gzip/;
use File::Slurp;

my $json = read_file('example.json', { binmode => ':raw' });
my $utf8_record = encode("utf8", $json);
my $output_data;
gzip \$utf8_record => \$output_data;
print $output_data;

知道我在 Perl 方面做错了什么吗?

您对 Perl 没有做错任何事。 您的 Python 代码和 Perl 代码都使用 gzip 正确压缩数据。 Only Perl prints the output as binary while your Python code prints a readable representation of the output, ie something like b"\x1f\x8b..." . 要获得与 Perl 类似的结果,您需要将二进制数据打印到 stdout 而不是字符串表示,即代替print(...)

sys.stdout.buffer.write(output_data)

然后两个程序都会将 gzip 压缩数据写入标准输出。 请注意,output 可能仍然不同,因为它们默认使用不同的 gzip 选项(压缩率、操作系统类型...),但在这两种情况下,数据都使用 gzip 正确压缩。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM