我将散列字符串存储在文件{"a"=>1,"b"=>2}中,我打开该文件并将此散列字符串存储到$hash_string中,如何将此$hash_string转换为$hash_string_ref = {"a"=>1,"b"=>2}
发布于 2013-02-27 17:27:12
发布于 2013-02-27 17:28:10
该模块将运行任何perl代码(在沙箱中)并返回结果。包括解码例如转储到文件的结构。
代码示例:
use Safe;
my $compartment = new Safe;
my $unsafe_code = '{"a"=>1,"b"=>2}';
my $result = $compartment->reval($unsafe_code);
print join(', ', %$result); 发布于 2013-02-27 18:44:56
您的数据格式似乎是“任意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');https://stackoverflow.com/questions/15108330
复制相似问题