簡體   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