如何将'hash string'转换为hash?

Sat*_*ato 3 perl

我有存储在文件中的哈希字符串{"a"=>1,"b"=>2},我打开文件并将此哈希字符串存储到$hash_string,如何将其转换$hash_string$hash_string_ref = {"a"=>1,"b"=>2}

Sim*_*ens 9

简单的答案:

$ echo '{"a"=>1,"b"=>2}' > val.pl
$ perl -le 'my $foo = do "val.pl"; print $foo->{a}'
1
Run Code Online (Sandbox Code Playgroud)

更好的答案:考虑使用更好的数据序列化格式,例如StorableYAML,甚至是JSON.


FtL*_*Lie 5

使用Perl Safe

该模块将运行任何perl-code(在沙箱中)并返回结果.包括解码,例如转储到文件的结构.

代码示例:

use Safe;     
my $compartment = new Safe;
my $unsafe_code = '{"a"=>1,"b"=>2}';
my $result = $compartment->reval($unsafe_code);
print join(', ', %$result); 
Run Code Online (Sandbox Code Playgroud)


ike*_*ami 5

您的数据格式似乎是"任意Perl表达式",这是一种非常糟糕的数据格式.为什么不使用JSON或更全面的YAML呢?

use JSON::XS qw( encode_json decode_json );

sub save_struct {
   my ($qfn, $data) = @_;
   open(my $fh, '>:raw', $qfn)
      or die("Can't create JSON file \"$qfn\": $!\n");
   print($fh encode_json($data))
      or die("Can't write JSON to file \"$qfn\": $!\n");
   close($fh)
      or die("Can't write JSON to file \"$qfn\": $!\n");
}

sub load_struct {
   my ($qfn) = @_;
   open(my $fh, '>:raw', $qfn)
      or die("Can't create JSON file \"$qfn\": $!\n");
   my $json; { local $/; $json = <$fh>; }
   return decode_json($json);
}

my $data = {"a"=>1,"b"=>2};
save_struct('file.json', $data);

...

my $data = load_struct('file.json');
Run Code Online (Sandbox Code Playgroud)