简体   繁体   English

如何使用数据转储器将简单的 hash 存储在 perl 中

[英]How can I store simple hash in perl using data dumper

%hash = ('abc' => 123, 'def' => [4,5,6]);

how can I store above hash in file using data dumper in Perl如何使用 Perl 中的数据转储器将 hash 以上存储在文件中

Files can only contain sequences of bytes, so you need to convert the data structure into a sequence of bytes somehow.文件只能包含字节序列,因此您需要以某种方式将数据结构转换为字节序列。 This process is called serialization.这个过程称为序列化。

The possibilities available to you are endless, but a few are worth mentioning:您可以使用的可能性是无穷无尽的,但有一些值得一提:

  • JSON is a very common choice. JSON 是一个很常见的选择。
  • YAML is more flexible. YAML 更灵活。
  • Storable is specifically made for Perl data structures. Storable专为 Perl 数据结构而设计。

There is also Data::Dumper, as you say.正如你所说,还有 Data::Dumper。

use Data::Dumper qw( );

sub serialize {
   my ($x) = @_;
   local $Data::Dumper::Purity = 1;    # Required for some data structures.
   local $Data::Dumper::Useqq = 1;     # Optional. Limits output to ASCII.
   local $Data::Dumper::Sortkeys = 1;  # Optional. Makes revision control easier.
   return Data::Dumper->Dump([$x], ["x"]);
}

print($fh serialize($x));

Data::Dumper isn't a particularly good choice, since there's no existing module to safely deserialize the structure in Perl [1] , and there's even less support outside of Perl. Data::Dumper 不是一个特别好的选择,因为没有现有的模块可以安全地反序列化 Perl [1]中的结构,而且 Perl 之外的支持更少。

sub deserialize {
   my ($s) = @_;
   my $x;
   eval($s);       # XXX Unsafe!
   die($@) if $@;
   return $x;
}

  1. If you're ok with limiting yourself to data structure JSON can serialize (by setting Purity to 0 ), then you could use Data::Undump to safely deserialize.如果您可以将自己限制在数据结构 JSON 可以序列化(通过将Purity设置为0 ),那么您可以使用Data::Undump安全地反序列化。 But then why not just use JSON?!但是为什么不直接使用 JSON?!
use Data::Dumper open (FL, ">", "file.txt") or die "Cant open file $! "; print FL Dumper \%hash; close FL;

"how can I store above hash in file using data dumper in Perl" “如何使用 Perl 中的数据转储器将 hash 存储在文件中”

Store it as JSON so it can be read back by (almost) anything, using Data::Dumper configured to print JSON.将其存储为 JSON 以便(几乎)任何东西都可以读取它,使用配置为打印 JSON 的Data::Dumper

use strict;
use warnings;
use Data::Dumper;

local $Data::Dumper::Pair = ' : ';
local $Data::Dumper::Quotekeys = 1;
local $Data::Dumper::Useqq = 1;
local $Data::Dumper::Terse = 1;

my %hash = ('abc' => 123, 'def' => [4,5,6]);

open my $file, '>', 'foo.json' or die $!;

print $file Dumper \%hash;

Output: Output:

$ cat foo.json
{
  "def" : [
             4,
             5,
             6
           ],
  "abc" : 123
}

(Note: I would of course rather use a dedicated JSON-handling module for this, but you asked....) (注意:我当然宁愿为此使用专用的 JSON 处理模块,但你问了......)

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

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