我想知道是否有人能提供以下python代码的Perl等价物,该代码将变量pickle和unpickle到文件中。
data = [( "somestring.data", (178346464,1234568) )]
serialized_data = cPickle.dumps(data, protocol=-1)
length_prefix = struct.pack("!L", len(serialized_data))
message = length_prefix + serialized_data
谢谢。
未测试。
use Python::Serialise::Pickle qw( );
# Work around P::S::Pickle 0.01's extremely limiting interface.
sub pickle_dumps {
open(my $fh, '>', my $s) or die $!;
my $pickle = bless({ _fh => $fh }, 'Python::Serialise::Pickle');
$pickle->dump($_[0]);
$pickle->close();
return $s;
}
my $data = [ "somestring.data", [ 178346464, 1234568 ] ];
my $message = pack("N/a*", pickle_dumps($data));
我认真研究perl已经很久了(超过十年)。
因此,我将描述:
- 数据是字符串和数组中整数数组的任意小数据结构
- 数据是使用二进制语言特定的打包方案(pickle)序列化的,该方案可以打包任意数据和代码
- 计算串行化数据的长度并将其转换为二进制格式big-endian 4字节
- 长度的二进制表示和序列化的数据被连接起来
看起来像是线路协议的基础。接收代码将读取4个字节,解压缩有效载荷长度,读取有效载荷长度字节。打开有效载荷的包装。
将perl变量序列化到文件:
$thing = "Something the one true Morty might say";
use Python::Serialise::Pickle qw( );
$file_location = "/home/some/file.pckl";
open my $file, '>', $file_location or die $!;
my $pickle = bless({ _fh => $file }, 'Python::Serialise::Pickle');
$pickle_out = $pickle->dump($thing);
print $file $pickle_out;
$pickle->close();
close $file;
文件内容:
.S'Something 40the 40one 40true 40Morty 40might 40say'
p0
.
将perl变量从文件反序列化回变量:
use Data::Dumper;
use Python::Serialize::Pickle::InlinePython;
$file_location = "/home/some/file.pckl";
my $pic = Python::Serialize::Pickle::InlinePython->new($file_location);
my $recovered_variable = $pic->load();
print "$recovered_variable: '" . $recovered_variable . "'n";
打印:
$recovered_variable: 'Something the one true Morty might say'