我有存储在文件{"a"=>1,"b"=>2}
中的哈希字符串,我打开文件并将此哈希字符串存储到$hash_string
,如何将此$hash_string
转换为$hash_string_ref = {"a"=>1,"b"=>2}
?
答案 0 :(得分:9)
简单的答案:
$ echo '{"a"=>1,"b"=>2}' > val.pl
$ perl -le 'my $foo = do "val.pl"; print $foo->{a}'
1
答案 1 :(得分:5)
模块将运行任何perl-code(在沙箱中)并返回结果。包括解码,例如转储到文件的结构。
代码示例:
use Safe;
my $compartment = new Safe;
my $unsafe_code = '{"a"=>1,"b"=>2}';
my $result = $compartment->reval($unsafe_code);
print join(', ', %$result);
答案 2 :(得分: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');