简体   繁体   中英

Perl equivalent for python encode and gzip

I am attempting to generate a compressed string in Perl that is equivalent to a string generated in Python.

Python (produces the correct output):

import gzip
test_file = 'example.json'

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

More or less what I've been trying to make work in 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;

Any idea what I'm doing wrong on the Perl side?

You don't do anything wrong with Perl. Both your Python code and your Perl code properly compress the data with 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..." . To get the similar result to Perl you would instead neee to print the binary data to stdout instead of the string representation, ie instead of print(...) do

sys.stdout.buffer.write(output_data)

Then both programs would write gzip compressed data to stdout. Note that the output might still differ since they use different options by default for gzip (compression ratio, OS type...) but the data are nevertheless properly compressed in both cases with gzip.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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